import logging
import sys

from django.contrib import messages
from NexusApp.models import AdminUser
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import redirect

from NexusApp.jwt_auth import clear_token_cookie, create_token, set_token_cookie

logger = logging.getLogger(__name__)


def _log_exception(prefix, **info):
    _, _, exc_tb = sys.exc_info()
    logger.error(
        f"{prefix}. {info}, file: {exc_tb.tb_frame.f_code.co_filename}, line: {exc_tb.tb_lineno}"
    )


def login_validate(request):

    if request.method != 'POST':
        return JsonResponse({
            'status': 'error',
            'message': 'Invalid request method'
        }, status=400)

    email = request.POST.get('email', '').strip()
    password = request.POST.get('password', '')

    errors = {}

    if not email:
        errors['email'] = 'Email is required.'
    elif '@' not in email:
        errors['email'] = 'Please enter a valid email address.'

    if not password:
        errors['password'] = 'Password is required.'

    if errors:
        return JsonResponse({
            'status': 'error',
            'errors': errors
        }, status=400)

    try:
        # Get admin from your custom AdminUser table
        admin = AdminUser.objects.filter(email__iexact=email).first()

        if not admin:
            return JsonResponse({
                'status': 'error',
                'errors': {'email': 'Email not found.'}
            }, status=400)

        # Check password using your custom model
        if not admin.check_password(password):
            return JsonResponse({
                'status': 'error',
                'errors': {'password': 'Incorrect password.'}
            }, status=400)

        # Create JWT token for custom AdminUser
        token = create_token(admin)

        response = JsonResponse({
            'status': 'success',
            'message': 'Login successful.',
            'redirect_url': '/admin/dashboard/',
        })

        return set_token_cookie(response, token)

    except Exception as e:
        logger.exception("Admin login failed")
        return JsonResponse({
            'status': 'error',
            'message': 'Something went wrong. Please try again.'
        }, status=500)

    
def reset_password_validate(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

    current_password = request.POST.get('current_password', '').strip()
    new_password = request.POST.get('new_password', '').strip()
    confirm_password = request.POST.get('confirm_password', '').strip()

    errors = {}
    if not current_password:
        errors['current_password'] = 'Current password is required.'
    if not new_password:
        errors['new_password'] = 'New password is required.'
    elif len(new_password) < 8:
        errors['new_password'] = 'The password must be at least 8 characters long.'
    if not confirm_password:
        errors['confirm_password'] = 'Confirm password is required.'
    elif new_password != confirm_password:
        errors['confirm_password'] = 'The password confirmation does not match.'
    if new_password and current_password and new_password == current_password:
        errors['new_password'] = 'The password must be different from current password.'
    if errors:
        return JsonResponse({'status': 'error', 'errors': errors}, status=400)

    user = request.user
    if not user.is_authenticated:
        return JsonResponse({'status': 'error', 'message': 'Please login again.'}, status=401)

    try:
        if not user.check_password(current_password):
            logger.warning(f"Reset password failed - current password incorrect. user: {user.email}")
            return JsonResponse({
                'status': 'error',
                'errors': {'current_password': 'Current password is incorrect.'},
            }, status=400)

        with transaction.atomic():
            user.set_password(new_password)
            user.save()

        logger.info(f"Password reset successful. user: {user.email}")

        # Old token stops working automatically (password changed); clear the cookie too.
        response = JsonResponse({
            'status': 'success',
            'message': 'Password reset successfully. Please login again.',
            'redirect_url': '/admin/admin_login/',
        })
        return clear_token_cookie(response)

    except Exception as e:
        _log_exception("Reset password failed with exception", user=user.email, error=str(e))
        return JsonResponse({'status': 'error', 'message': 'Something went wrong. Please try again.'}, status=500)


def admin_logout(request):
    try:
        email = request.user.email if request.user.is_authenticated else None
        logger.info(f"logout successful. email: {email}")
        messages.success(request, "logout successful")
        response = redirect("admin:admin_login") # Ensure namespaced redirect if needed
        return clear_token_cookie(response)
    except Exception as e:
        logger.error(f"logout failed: {e}")
        messages.error(request, "unable to logout please try again.")
        return redirect(request.META.get("HTTP_REFERER", "admin:admin_login"))