from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Sum
from django.utils.timezone import now
from bookkeeping.models import Income, Expense


def home(request):
    return render(request, "home.html")


@login_required
def dashboard(request):
    """
    Dashboard view for MTDify Starter Edition.
    Shows totals for the current tax year + quarter figures + recent items.
    """

    user = request.user
    today = now().date()

    # -------------------------------
    # Determine start of tax year
    # -------------------------------
    if today.month < 4 or (today.month == 4 and today.day < 6):
        tax_year_start = today.replace(year=today.year - 1, month=4, day=6)
        tax_year_label = f"{today.year - 1}-{today.year}"
    else:
        tax_year_start = today.replace(month=4, day=6)
        tax_year_label = f"{today.year}-{today.year + 1}"

    # -------------------------------
    # YTD totals
    # -------------------------------
    ytd_income = (
        Income.objects.filter(user=user, date__gte=tax_year_start)
        .aggregate(total=Sum("amount"))
        .get("total")
        or 0
    )

    ytd_expenses = (
        Expense.objects.filter(user=user, date__gte=tax_year_start)
        .aggregate(total=Sum("amount"))
        .get("total")
        or 0
    )

    ytd_profit = ytd_income - ytd_expenses

    # -------------------------------
    # Determine current quarter
    # -------------------------------
    # We can determine the quarter based on the most recent income/expense entry
    latest_q_income = (
        Income.objects.filter(user=user)
        .order_by("-date")
        .values_list("quarter", flat=True)
        .first()
    )
    latest_q_expense = (
        Expense.objects.filter(user=user)
        .order_by("-date")
        .values_list("quarter", flat=True)
        .first()
    )

    current_quarter = latest_q_income or latest_q_expense or "N/A"

    # -------------------------------
    # Quarter totals
    # -------------------------------
    quarter_income = (
        Income.objects.filter(user=user, quarter=current_quarter)
        .aggregate(total=Sum("amount"))
        .get("total")
        or 0
    )

    quarter_expenses = (
        Expense.objects.filter(user=user, quarter=current_quarter)
        .aggregate(total=Sum("amount"))
        .get("total")
        or 0
    )

    quarter_profit = quarter_income - quarter_expenses

    # -------------------------------
    # Business count (needed for template)
    # -------------------------------
    business_count = 1  # local-first = ONE business only

    # -------------------------------
    # Recent items
    # -------------------------------
    recent_income = Income.objects.filter(user=user).order_by("-date")[:5]
    recent_expenses = Expense.objects.filter(user=user).order_by("-date")[:5]

    # -------------------------------
    # Send everything to template
    # -------------------------------
    context = {
        # quarter
        "current_quarter": current_quarter,
        "quarter_income": quarter_income,
        "quarter_expenses": quarter_expenses,
        "quarter_profit": quarter_profit,
        # year-to-date
        "ytd_income": ytd_income,
        "ytd_expenses": ytd_expenses,
        "ytd_profit": ytd_profit,
        "tax_year": tax_year_label,
        # existing fields (keep these!)
        "total_income": ytd_income,
        "total_expenses": ytd_expenses,
        "business_count": business_count,
        "recent_income": recent_income,
        "recent_expenses": recent_expenses,
    }

    return render(request, "dashboard.html", context)
