from django.contrib.auth import views as auth_views, login as auth_login
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.utils import timezone
from django.views import View

from core.magic_auth import MagicLinkToken, send_magic_link


class LoginView(View):
    """
    Unified login page with two options:
    1. Magic Link (enter email, receive login link)
    2. Traditional username/password
    Displayed as selectable cards; user picks their method.
    """
    def get(self, request):
        if request.user.is_authenticated:
            return redirect('/dashboard/')
        return render(request, 'auth/login.html')

    def post(self, request):
        """Handle traditional username/password login."""
        from django.contrib.auth import authenticate
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '')

        user = authenticate(request, username=username, password=password)
        if user is not None:
            auth_login(request, user, backend='core.magic_auth.EmailBackend')
            return redirect('/dashboard/')

        return render(request, 'auth/login.html', {
            'login_error': 'Invalid username/email or password.',
            'active_method': 'password',
        })


class MagicLinkSendView(View):
    """POST: Send a magic link email to the provided address."""
    def post(self, request):
        email = request.POST.get('email', '').strip().lower()

        if not email:
            return render(request, 'auth/login.html', {
                'magic_error': 'Please enter your email address.',
                'active_method': 'magic',
            })

        # Check if a user with this email exists
        if not User.objects.filter(email=email).exists():
            # Don't reveal whether email exists — show same success message
            return render(request, 'auth/login.html', {
                'magic_sent': True,
                'magic_email': email,
                'active_method': 'magic',
            })

        token_obj = send_magic_link(email, request)
        if not token_obj:
            return render(request, 'auth/login.html', {
                'magic_error': 'Could not send email right now. Please check your network or try logging in with password.',
                'active_method': 'magic',
            })

        return render(request, 'auth/login.html', {
            'magic_sent': True,
            'magic_email': email,
            'active_method': 'magic',
        })


class MagicLinkVerifyView(View):
    """GET: Validate magic link token, log the user in, redirect to dashboard."""
    def get(self, request, token):
        try:
            token_obj = MagicLinkToken.objects.get(token=token)
        except MagicLinkToken.DoesNotExist:
            return render(request, 'auth/login.html', {
                'magic_error': 'Invalid login link. Please request a new one.',
                'active_method': 'magic',
            })

        if token_obj.used:
            return render(request, 'auth/login.html', {
                'magic_error': 'This login link has already been used. Please request a new one.',
                'active_method': 'magic',
            })

        if token_obj.is_expired:
            return render(request, 'auth/login.html', {
                'magic_error': 'This login link has expired. Please request a new one.',
                'active_method': 'magic',
            })

        # Mark token as used
        token_obj.used = True
        token_obj.save(update_fields=['used'])

        # Find and log in the user
        try:
            user = User.objects.get(email=token_obj.email)
        except User.DoesNotExist:
            return render(request, 'auth/login.html', {
                'magic_error': 'No account found for this email. Please book a sale to get started.',
                'active_method': 'magic',
            })

        auth_login(request, user, backend='core.magic_auth.EmailBackend')
        return redirect('/dashboard/')


class LogoutView(auth_views.LogoutView):
    next_page = '/'
