import json
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, get_user_model, login, logout
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt

from .models import UserProfile
from campus.models import Enrollment
from courses.models import Course


def login_view(request):
    """
    Pantalla ejecutiva de ingreso al ecosistema E-Learning y Portal Docente.
    """
    if request.user.is_authenticated:
        if hasattr(request.user, 'profile') and not request.user.profile.is_student:
            return redirect("studio:studio_dashboard")
        return redirect("campus:portal_elearning")

    next_url = request.GET.get("next") or request.POST.get("next", "")

    if request.method == "POST":
        username_or_email = request.POST.get("username", "").strip()
        password = request.POST.get("password", "")

        user = authenticate(request, username=username_or_email, password=password)
        if not user:
            # Intentar por correo
            User = get_user_model()
            user_by_email = User.objects.filter(email__iexact=username_or_email).first()
            if user_by_email:
                user = authenticate(request, username=user_by_email.username, password=password)

        if user and user.is_active:
            login(request, user)
            messages.success(request, f"¡Bienvenido de nuevo, {user.first_name or user.username}!")
            if next_url:
                return redirect(next_url)
            if hasattr(user, 'profile') and not user.profile.is_student:
                return redirect("studio:studio_dashboard")
            return redirect("campus:portal_elearning")
        else:
            messages.error(request, "Usuario/Correo o contraseña incorrectos. Verifica tus credenciales.")

    return render(request, "pages/auth/login.html", {"next": next_url})


def register_view(request):
    """
    Registro rápido para alumnos y técnicos de empresas o particulares.
    """
    if request.user.is_authenticated:
        return redirect("campus:portal_elearning")

    if request.method == "POST":
        first_name = request.POST.get("first_name", "").strip()
        last_name = request.POST.get("last_name", "").strip()
        email = request.POST.get("email", "").strip()
        rut = request.POST.get("rut", "").strip()
        company = request.POST.get("company", "").strip()
        position_title = request.POST.get("position_title", "").strip()
        password = request.POST.get("password", "")
        password_confirm = request.POST.get("password_confirm", "")

        User = get_user_model()

        if not email or not password or not first_name:
            messages.error(request, "Los campos Nombre, Correo y Contraseña son obligatorios.")
            return render(request, "pages/auth/register.html", request.POST)

        if password != password_confirm:
            messages.error(request, "Las contraseñas no coinciden.")
            return render(request, "pages/auth/register.html", request.POST)

        if User.objects.filter(email__iexact=email).exists():
            messages.error(request, "Este correo ya se encuentra registrado en el LMS.")
            return render(request, "pages/auth/register.html", request.POST)

        username = email.split("@")[0]
        base_username = username
        counter = 1
        while User.objects.filter(username=username).exists():
            username = f"{base_username}{counter}"
            counter += 1

        user = User.objects.create_user(
            username=username,
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name
        )

        profile, _ = UserProfile.objects.get_or_create(user=user)
        profile.role = 'STUDENT'
        profile.rut = rut
        profile.company = company
        profile.position_title = position_title
        profile.save()

        login(request, user)
        messages.success(request, "¡Tu cuenta ha sido creada exitosamente! Bienvenido a Lo Justo LMS.")
        return redirect("campus:portal_elearning")

    return render(request, "pages/auth/register.html")


def logout_view(request):
    """
    Cierre de sesión y regreso a la Landing Page institucional.
    """
    logout(request)
    messages.info(request, "Has cerrado sesión correctamente.")
    return redirect("core:landing")


@csrf_exempt
def sync_users_view(request):
    """
    Webhook / API para la sincronización automática de técnicos desde el ERP o RRHH.
    """
    if request.method != "POST":
        return JsonResponse({"error": "Only POST allowed"}, status=405)

    api_key = request.headers.get("X-API-KEY")
    expected_key = getattr(settings, "SECRET_INTEGRATION_KEY", "lojusto-secret-sync-key-2026")

    if api_key != expected_key:
        return JsonResponse({"error": "Unauthorized / Invalid X-API-KEY"}, status=401)

    try:
        data = json.loads(request.body.decode("utf-8"))
    except Exception:
        return JsonResponse({"error": "Invalid JSON payload"}, status=400)

    email = data.get("email") or data.get("external_rut", "") + "@lojustosac.com"
    username = data.get("external_rut") or email.split("@")[0]

    User = get_user_model()
    user, created = User.objects.get_or_create(
        username=username,
        defaults={
            "email": email,
            "first_name": data.get("first_name", ""),
            "last_name": data.get("last_name", ""),
        }
    )
    if not created:
        if data.get("first_name"): user.first_name = data["first_name"]
        if data.get("last_name"): user.last_name = data["last_name"]
        if data.get("email"): user.email = data["email"]
        user.save()

    enrolled_slugs = []
    assign_courses = data.get("assign_courses", [])
    if isinstance(assign_courses, list):
        for slug in assign_courses:
            course = Course.objects.filter(slug=slug).first()
            if course:
                Enrollment.objects.get_or_create(user=user, course=course)
                enrolled_slugs.append(course.slug)

    return JsonResponse({
        "status": "success",
        "action": "created" if created else "updated",
        "username": user.username,
        "full_name": user.get_full_name(),
        "enrolled_courses": enrolled_slugs
    })
