from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import JsonResponse
from django.utils import timezone
from datetime import timedelta

from .forms import ForgotPasswordForm, ResetPasswordForm
from .models import PasswordReset
from .utils import send_password_reset_email

# -------------------------
# PASSWORD RESET VIEWS
# -------------------------
def forgot_password_view(request):
    if request.user.is_authenticated:
        return redirect('home')
        
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            try:
                user = User.objects.get(email=email)
                
                # Create password reset token
                reset_token = PasswordReset.objects.create(
                    user=user,
                    expires_at=timezone.now() + timedelta(hours=24)
                )
                
                # Send email
                if send_password_reset_email(request, user, reset_token):
                    messages.success(
                        request,
                        "Password reset instructions have been sent to your email address."
                    )
                else:
                    messages.error(
                        request,
                        "Failed to send password reset email. Please try again later."
                    )
                    
                return redirect('login')
                
            except User.DoesNotExist:
                messages.error(request, "No account found with this email address.")
    else:
        form = ForgotPasswordForm()
    
    return render(request, 'reset.html', {'form': form})

def reset_password_view(request, token):
    # Allow password reset even if user is logged in
    # if request.user.is_authenticated:
    #     return redirect('home')
    
    try:
        reset_token = PasswordReset.objects.get(token=token)
        
        if not reset_token.is_valid():
            messages.error(request, "This password reset link has expired or is invalid.")
            return redirect('login')
            
        if request.method == 'POST':
            form = ResetPasswordForm(request.POST)
            if form.is_valid():
                # Update user password
                user = reset_token.user
                user.set_password(form.cleaned_data['password1'])
                user.save()
                
                # Mark token as used
                reset_token.used = True
                reset_token.save()
                
                messages.success(
                    request,
                    "Your password has been reset successfully. You can now log in with your new password."
                )
                return redirect('login')
            else:
                # Form is invalid, render template with errors
                return render(request, 'basic_reset.html', {
                    'form': form,
                    'token': token,
                    'user': reset_token.user
                })
        else:
            form = ResetPasswordForm()
            
        return render(request, 'basic_reset.html', {
            'form': form,
            'token': token,
            'user': reset_token.user
        })
        
    except PasswordReset.DoesNotExist:
        messages.error(request, "Invalid password reset link.")
        return redirect('login')
    except Exception as e:
        messages.error(request, "An error occurred. Please try again.")
        return redirect('login')

# -------------------------
# EMAIL VERIFICATION (DISABLED)
# -------------------------
def verify_email_view(request, token):
    messages.error(request, "Email verification functionality is currently disabled.")
    return redirect('login')