import { useEffect, useMemo, useState } from "react";
import { format } from "date-fns";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Receipt, Download, FileText, AlertCircle } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { useToast } from "@/hooks/use-toast";
import { parseLocalDate } from "@/lib/dateUtils";
import { generateLedgerStatement } from "@/components/unit-profile/UnitLedgerStatementPDF";

interface LedgerEntry {
  id: string;
  date: string;
  created_at: string;
  description: string | null;
  transaction_type: string | null;
  debit: number | null;
  credit: number | null;
}

export default function HomeownerStatementsPage() {
  const { currentOwner, association, unit, loading: contextLoading } = useHomeowner();
  const { toast } = useToast();
  const [entries, setEntries] = useState<LedgerEntry[]>([]);
  const [owners, setOwners] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (contextLoading) return;
    if (!currentOwner) {
      setEntries([]);
      setOwners([]);
      setLoading(false);
      return;
    }

    const fetchStatementData = async () => {
      setLoading(true);
      const ledgerQuery = supabase
        .from("owner_ledger_entries")
        .select("id, date, created_at, description, transaction_type, debit, credit")
        .order("date", { ascending: true })
        .order("created_at", { ascending: true });

      const [entriesRes, ownersRes] = await Promise.all([
        unit?.id ? ledgerQuery.eq("unit_id", unit.id) : ledgerQuery.eq("owner_id", currentOwner.id),
        unit?.id
          ? supabase.from("owners").select("id, first_name, last_name, is_primary").eq("unit_id", unit.id).eq("status", "active")
          : Promise.resolve({ data: [currentOwner], error: null }),
      ]);

      if (entriesRes.error) {
        toast({ variant: "destructive", title: "Statements unavailable", description: entriesRes.error.message });
        setEntries([]);
      } else {
        setEntries(entriesRes.data || []);
      }

      if (!ownersRes.error) setOwners(ownersRes.data || []);
      setLoading(false);
    };

    fetchStatementData();
  }, [contextLoading, currentOwner, unit?.id, toast]);

  const statementPeriods = useMemo(() => {
    const sorted = [...entries].sort((a, b) =>
      a.date === b.date ? a.created_at.localeCompare(b.created_at) : a.date.localeCompare(b.date)
    );

    const byMonth = new Map<string, LedgerEntry[]>();
    for (const entry of sorted) {
      const monthKey = format(parseLocalDate(entry.date), "yyyy-MM");
      byMonth.set(monthKey, [...(byMonth.get(monthKey) || []), entry]);
    }

    return Array.from(byMonth.entries())
      .sort(([left], [right]) => right.localeCompare(left))
      .slice(0, 12)
      .map(([key]) => {
        // All entries through the end of this month (cumulative statement)
        const cumulative = sorted.filter((e) => format(parseLocalDate(e.date), "yyyy-MM") <= key);
        const monthOnly = byMonth.get(key) || [];
        return {
          key,
          label: format(parseLocalDate(`${key}-01`), "MMMM yyyy"),
          entries: cumulative,
          charges: monthOnly.reduce((sum, entry) => sum + Number(entry.debit || 0), 0),
          credits: monthOnly.reduce((sum, entry) => sum + Number(entry.credit || 0), 0),
        };
      });
  }, [entries]);

  const downloadStatement = (periodEntries = entries) => {
    if (!unit || periodEntries.length === 0) return;
    try {
      generateLedgerStatement({
        unitData: unit,
        owners: owners.length ? owners : [currentOwner],
        entries: periodEntries,
        associationName: association?.name,
      });
    } catch (error: any) {
      toast({ variant: "destructive", title: "Download failed", description: error.message || "Could not generate statement." });
    }
  };

  if (contextLoading || loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!currentOwner) {
    return (
      <div className="text-center py-20 space-y-2">
        <AlertCircle className="h-10 w-10 text-muted-foreground/30 mx-auto" />
        <p className="text-lg font-medium text-foreground">No property linked to your account</p>
        <p className="text-sm text-muted-foreground">Please contact your property management company.</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Receipt className="w-6 h-6 text-primary" /> Account Statements
          </h1>
          <p className="text-muted-foreground mt-1">View and download your monthly statements and ledgers.</p>
        </div>
        <Button variant="outline" className="gap-2" onClick={() => downloadStatement()} disabled={entries.length === 0}>
          <Download className="w-4 h-4" /> Download Full Ledger
        </Button>
      </div>

      <Card>
        <CardHeader className="border-b bg-muted/50">
          <CardTitle className="text-lg">Recent Statements</CardTitle>
          <CardDescription>Your generated statements for the past 12 months.</CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          {statementPeriods.length === 0 ? (
            <div className="p-12 text-center flex flex-col items-center">
              <div className="bg-muted p-4 rounded-full mb-3">
                <FileText className="w-8 h-8 text-muted-foreground" />
              </div>
              <p className="text-muted-foreground font-medium">No statements available.</p>
              <p className="text-sm text-muted-foreground mt-1">No ledger activity has been posted for this property yet.</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Statement Period</TableHead>
                  <TableHead className="text-right">Charges</TableHead>
                  <TableHead className="text-right">Credits</TableHead>
                  <TableHead className="text-right">Net Activity</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {statementPeriods.map((period) => (
                  <TableRow key={period.key}>
                    <TableCell className="font-medium">{period.label}</TableCell>
                    <TableCell className="text-right">${period.charges.toFixed(2)}</TableCell>
                    <TableCell className="text-right">${period.credits.toFixed(2)}</TableCell>
                    <TableCell className="text-right">${(period.charges - period.credits).toFixed(2)}</TableCell>
                    <TableCell className="text-right">
                      <Button variant="ghost" size="sm" className="gap-2" onClick={() => downloadStatement(period.entries)}>
                        <Download className="w-4 h-4" /> Download
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
