from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse

from django.db.models import Sum

from payments.models import Payment, Invoice, Expense
from maintenance.models import Complaint, RepairRequest
from properties.models import Unit, Building
from accounts.models import User
from tenants.models import TenantProfile

from .services import (
    get_financial_summary,
    get_cached_financial_summary,   # ✅ NEW (Redis)
    get_arrears_report,
    get_expense_breakdown,
    get_profit_loss,
    get_occupancy_metrics,
    get_unit_performance,
    get_tenant_behavior,
    get_maintenance_summary,
    get_cost_loss_analysis,
    get_tax_summary,
)

from .utils import (
    get_filtered_payments,
    get_filtered_expenses,
    resolve_date_filter,
)


# =====================================================
# 🔹 ACCESS CONTROL
# =====================================================

def reports_access_required(user):
    return user.role in ["landlord", "caretaker"]


# =====================================================
# 🔹 SIMPLE LANDLORD SNAPSHOT (LEGACY SAFE)
# =====================================================

@login_required
def landlord_report(request):
    total_collected = Payment.objects.aggregate(Sum('amount'))['amount__sum'] or 0
    pending = Invoice.objects.filter(status='pending').count()
    complaints = Complaint.objects.count()
    repairs = RepairRequest.objects.count()

    return render(request, 'reports/landlord_report.html', {
        'total_collected': total_collected,
        'pending_invoices': pending,
        'complaints': complaints,
        'repairs': repairs,
    })


# =====================================================
# 🔹 MAIN DASHBOARD (CACHED)
# =====================================================

@login_required
def reports_dashboard(request):
    if not reports_access_required(request.user):
        return redirect("login")

    start_date, end_date = resolve_date_filter(request)

    filters = {
        "start_date": start_date,
        "end_date": end_date,
    }

    # ✅ USE REDIS-CACHED DATA
    financial = get_cached_financial_summary(filters)

    arrears = get_arrears_report(filters)
    occupancy = get_occupancy_metrics(filters)

    active_tenants = TenantProfile.objects.filter(
        unit__isnull=False
    ).count()

    return render(request, "reports/dashboard.html", {
        "financial": financial,
        "arrears": arrears,
        "occupancy": occupancy,
        "active_tenants": active_tenants,
    })


# =====================================================
# 🔹 FINANCIAL REPORT
# =====================================================

@login_required
def financial_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

    start_date, end_date = resolve_date_filter(request)

    filters = {
        "start_date": start_date,
        "end_date": end_date,
    }

    financial = get_financial_summary(filters)
    arrears = get_arrears_report(filters)
    expenses = get_expense_breakdown(filters)
    profit = get_profit_loss(filters)

    return render(request, "reports/financial_report.html", {
        "financial": financial,
        "arrears": arrears,
        "expenses": expenses,
        "profit": profit,
    })


# =====================================================
# 🔹 UNIT PERFORMANCE REPORT
# =====================================================

@login_required
def unit_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

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

    data = [get_unit_performance(unit) for unit in units]

    return render(request, "reports/unit_report.html", {
        "data": data
    })


# =====================================================
# 🔹 TENANT ANALYTICS
# =====================================================

@login_required
def tenant_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

    tenants = User.objects.filter(role="tenant")

    data = [get_tenant_behavior(t) for t in tenants]

    return render(request, "reports/tenant_report.html", {
        "data": data
    })


# =====================================================
# 🔹 MAINTENANCE REPORT
# =====================================================

@login_required
def maintenance_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

    summary = get_maintenance_summary()
    loss = get_cost_loss_analysis()

    return render(request, "reports/maintenance_report.html", {
        "summary": summary,
        "loss": loss,
    })


# =====================================================
# 🔹 TAX REPORT (CRITICAL LOGIC)
# =====================================================

@login_required
def tax_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

    tax_mode = request.GET.get("mode", "mri")
    is_company = request.GET.get("company") == "true"

    start_date, end_date = resolve_date_filter(request)

    filters = {
        "start_date": start_date,
        "end_date": end_date,
    }

    tax_data = get_tax_summary(filters, tax_mode, is_company)

    return render(request, "reports/tax_report.html", {
        "tax": tax_data,
        "mode": tax_mode,
    })


# =====================================================
# 🔹 BUILDING FILTER SUPPORT
# =====================================================

@login_required
def building_filter_data(request):
    if not reports_access_required(request.user):
        return redirect("login")

    if request.user.role == "landlord":
        buildings = Building.objects.filter(landlord=request.user)
    else:
        buildings = Building.objects.filter(caretaker=request.user)

    units = Unit.objects.filter(building__in=buildings)

    return render(request, "reports/partials/building_filter.html", {
        "buildings": buildings,
        "units": units,
    })


# =====================================================
# 🔹 EXPORT HOOK
# =====================================================

@login_required
def export_report(request):
    if not reports_access_required(request.user):
        return redirect("login")

    report_type = request.GET.get("type")

    messages.info(request, f"{report_type} export processing started")

    return redirect("reports_dashboard")


# =====================================================
# 🔹 CHART APIs (FOR CHART.JS)
# =====================================================

@login_required
def income_vs_expense_chart(request):
    payments = get_filtered_payments(request, request.user)
    expenses = get_filtered_expenses(request, request.user)

    data = {}

    for p in payments:
        key = p.created_at.date().isoformat()
        data.setdefault(key, {"income": 0, "expense": 0})
        data[key]["income"] += float(p.amount)

    for e in expenses:
        key = e.created_at.date().isoformat()
        data.setdefault(key, {"income": 0, "expense": 0})
        data[key]["expense"] += float(e.amount)

    labels = sorted(data.keys())

    return JsonResponse({
        "labels": labels,
        "income": [data[d]["income"] for d in labels],
        "expenses": [data[d]["expense"] for d in labels],
    })


@login_required
def expense_breakdown_chart(request):
    expenses = get_filtered_expenses(request, request.user)

    breakdown = {}

    for e in expenses:
        cat = e.category.name if e.category else "Other"
        breakdown[cat] = breakdown.get(cat, 0) + float(e.amount)

    return JsonResponse({
        "labels": list(breakdown.keys()),
        "data": list(breakdown.values())
    })