# maintenance/views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Complaint, RepairRequest
from properties.models import Unit


# ================= COMPLAINTS =================

@login_required
def create_complaint(request):

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

    # ✅ GET TENANT UNIT FROM SYSTEM (NOT FORM)
    profile = getattr(request.user, "tenantprofile", None)
    unit = getattr(profile, "unit", None) if profile else None

    if request.method == 'POST':

        if not unit:
            messages.error(request, "You are not assigned to any unit.")
            return redirect('tenant_dashboard')

        Complaint.objects.create(
            tenant=request.user,
            unit=unit,
            category=request.POST.get('category'),
            description=request.POST.get('description')
        )

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

    return render(request, 'maintenance/complaint.html')

@login_required
def complaint_list(request):
    user = request.user

    if user.role == 'tenant':
        complaints = Complaint.objects.filter(tenant=user)

    elif user.role in ['caretaker', 'landlord']:
        complaints = Complaint.objects.select_related('tenant', 'unit')

    else:
        complaints = Complaint.objects.none()

    return render(request, 'maintenance/complaint_list.html', {
        'complaints': complaints
    })


@login_required
def mark_complaint_in_progress(request, complaint_id):
    complaint = get_object_or_404(Complaint, id=complaint_id)

    if request.user.role in ['caretaker', 'landlord'] and complaint.status == 'open':
        complaint.status = 'in_progress'
        complaint.save()

        messages.info(request, "Complaint marked as in progress.")

    return redirect('complaint_list')


@login_required
def resolve_complaint(request, complaint_id):
    complaint = get_object_or_404(Complaint, id=complaint_id)

    if request.user.role in ['caretaker', 'landlord'] and complaint.status != 'resolved':
        complaint.status = 'resolved'
        complaint.save()

        messages.success(request, f"Complaint resolved for {complaint.tenant.username}")

    return redirect('complaint_list')


# ================= REPAIRS =================

@login_required
def create_repair_request(request):
    if request.method == 'POST':
        unit_id = request.POST.get('unit')
        unit = Unit.objects.filter(id=unit_id).first()

        if not unit:
            messages.error(request, "Invalid unit.")
            return redirect('repair')

        RepairRequest.objects.create(
            tenant=request.user,
            unit=unit,
            issue=request.POST.get('issue'),
            image=request.FILES.get('image')
        )

        messages.success(request, "Repair request submitted.")
        return redirect('tenant_dashboard')

    return render(request, 'maintenance/repair.html')


@login_required
def repair_list(request):
    user = request.user

    if user.role == 'tenant':
        repairs = RepairRequest.objects.filter(tenant=user)

    else:
        repairs = RepairRequest.objects.select_related('tenant', 'unit')

    return render(request, 'maintenance/repair_list.html', {
        'repairs': repairs
    })


@login_required
def approve_repair(request, repair_id):
    repair = get_object_or_404(RepairRequest, id=repair_id)

    if request.user.role == 'caretaker' and repair.status == 'pending':
        repair.status = 'approved'
        repair.save()
        messages.success(request, "Repair approved.")

    return redirect('repair_list')


@login_required
def reject_repair(request, repair_id):
    repair = get_object_or_404(RepairRequest, id=repair_id)

    if request.user.role == 'caretaker' and repair.status == 'pending':
        repair.status = 'rejected'
        repair.save()
        messages.warning(request, "Repair rejected.")

    return redirect('repair_list')


@login_required
def add_repair_cost(request, repair_id):
    repair = get_object_or_404(RepairRequest, id=repair_id)

    if request.user.role != 'landlord' or repair.status != 'approved':
        return redirect('repair_list')

    if request.method == 'POST':
        try:
            cost = float(request.POST.get('cost'))
        except (TypeError, ValueError):
            messages.error(request, "Invalid cost value.")
            return redirect('add_repair_cost', repair_id=repair.id)

        repair.cost = cost
        repair.status = 'completed'
        repair.save()

        messages.success(request, "Repair marked as completed.")
        return redirect('repair_list')

    return render(request, 'maintenance/add_cost.html', {
        'repair': repair
    })