from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import get_user_model

from .forms import TenantOnboardingForm
from .models import TenantApplication, TenantProfile

from core.models import ActivityLog
from payments.models import Payment
from maintenance.models import Complaint, RepairRequest
from properties.models import Building, Unit

User = get_user_model()


# =========================
# ONBOARDING
# =========================
@login_required
def tenant_onboarding(request):

    if request.user.role != "tenant":
        return redirect("login")

    profile, _ = TenantProfile.objects.get_or_create(user=request.user)

    # already completed onboarding
    if profile.id_image:
        return redirect("tenant_dashboard")

    if request.method == 'POST':
        form = TenantOnboardingForm(request.POST, request.FILES)

        if form.is_valid():
            data = form.cleaned_data

            # update profile safely
            profile.id_image = data.get("id_image")
            profile.emergency_contact = data.get("emergency_contact")
            profile.mpesa_number = data.get("mpesa_number")
            profile.save()

            # prevent duplicate applications per onboarding session
            TenantApplication.objects.create(
                user=request.user,
                full_name=request.user.get_full_name(),
                id_number=profile.id_number,
                id_image=profile.id_image,
                emergency_contact=profile.emergency_contact,
                mpesa_number=profile.mpesa_number,
                occupants=profile.occupants,
                status="pending"
            )

            messages.success(request, "Onboarding submitted successfully.")
            return redirect("tenant_dashboard")

    else:
        form = TenantOnboardingForm()

    return render(request, 'tenants/onboarding.html', {
        'form': form,
        'profile': profile
    })


# =========================
# APPROVAL
# =========================
@login_required
def approve_tenant(request, app_id):

    if request.user.role not in ["landlord", "caretaker"]:
        return redirect("login")

    application = get_object_or_404(TenantApplication, id=app_id)

    application.status = 'approved'
    application.save()

    profile, _ = TenantProfile.objects.get_or_create(user=application.user)

    # only assign unit if available and not already assigned
    if application.unit and not profile.unit:
        profile.unit = application.unit
        profile.save()

    ActivityLog.objects.create(
        user=request.user,
        action='approval',
        description=f"Approved tenant {application.user.username}"
    )

    return redirect('tenant_applications')


# =========================
# APPLICATION LIST
# =========================
@login_required
def tenant_applications(request):

    if request.user.role not in ["landlord", "caretaker"]:
        return redirect("login")

    applications = TenantApplication.objects.select_related("user", "unit").order_by("-submitted_at")

    return render(request, "tenants/tenant_applications.html", {
        "applications": applications
    })


# =========================
# REJECT
# =========================
@login_required
def reject_tenant(request, app_id):

    if request.user.role not in ["landlord", "caretaker"]:
        return redirect("login")

    application = get_object_or_404(TenantApplication, id=app_id)
    application.status = 'rejected'
    application.save()

    return redirect('tenant_applications')


# =========================
# TENANT DETAIL
# =========================
@login_required
def tenant_detail(request, user_id):

    tenant_user = get_object_or_404(User, id=user_id, role="tenant")

    profile = TenantProfile.objects.filter(user=tenant_user).first()

    payments = Payment.objects.filter(tenant=tenant_user).select_related("invoice").order_by("-created_at")
    complaints = Complaint.objects.filter(tenant=tenant_user).order_by("-created_at")
    repairs = RepairRequest.objects.filter(tenant=tenant_user).order_by("-created_at")

    rent_status = "Paid" if payments.exists() else "Unpaid"

    return render(request, "tenants/tenant_detail.html", {
        "tenant": tenant_user,
        "profile": profile,
        "payments": payments,
        "complaints": complaints,
        "repairs": repairs,
        "rent_status": rent_status
    })


# =========================
# ASSIGN FROM TENANT
# =========================
@login_required
def assign_from_tenant(request, tenant_id):

    tenant = get_object_or_404(User, id=tenant_id, role="tenant")
    profile = TenantProfile.objects.filter(user=tenant).first()

    if not profile or not profile.id_image:
        messages.error(request, "Tenant must complete onboarding first")
        return redirect("tenant_onboarding")

    if request.method == "POST":
        unit_id = request.POST.get("unit")
        unit = get_object_or_404(Unit, id=unit_id)

        if unit.is_full():
            messages.error(request, "Unit is full")
            return redirect("tenant_detail", tenant.id)

        return redirect("assign_tenant_finalize", tenant.id, unit.id)

    buildings = Building.objects.all()
    units = Unit.objects.select_related("building").all()

    return render(request, "tenants/select_unit.html", {
        "tenant": tenant,
        "profile": profile,
        "buildings": buildings,
        "units": units
    })