import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { BarChart3, TrendingUp, TrendingDown } from "lucide-react";
import { buildLedgerAccountBreakdown, type LedgerBreakdownEntry } from "@/lib/unitLedgerAccountBreakdown";

interface Props {
  unitId: string;
}

export default function UnitLedgerAccountBreakdown({ unitId }: Props) {
  const [entries, setEntries] = useState<LedgerBreakdownEntry[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!unitId) return;
    const fetchData = async () => {
      setLoading(true);
      // Account breakdown reflects the active ledger only — exclude entries from archived owners.
      const { data } = await supabase
        .from("owner_ledger_entries")
        .select("id, transaction_type, description, debit, credit, date, created_at, owners!inner(status)")
        .eq("unit_id", unitId)
        .eq("owners.status", "active")
        .order("date", { ascending: true })
        .order("created_at", { ascending: true })
        .order("id", { ascending: true });
      setEntries(data || []);
      setLoading(false);
    };
    fetchData();
  }, [unitId]);

  const { rows, totals, totalPayments } = useMemo(() => buildLedgerAccountBreakdown(entries), [entries]);

  if (loading) {
    return (
      <div className="space-y-3">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Summary cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card className="border shadow-sm">
          <CardContent className="p-5 flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-destructive/10 text-destructive">
              <TrendingUp className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Total Charges</p>
              <p className="text-2xl font-bold">${totals.charges.toFixed(2)}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="border shadow-sm">
          <CardContent className="p-5 flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-emerald-500/10 text-emerald-600">
              <TrendingDown className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Total Payments</p>
              <p className="text-2xl font-bold">${totalPayments.toFixed(2)}</p>
            </div>
          </CardContent>
        </Card>
        <Card className={`border shadow-sm ${totals.openBalance > 0 ? "border-destructive/30" : "border-emerald-500/30"}`}>
          <CardContent className="p-5 flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-primary/10 text-primary">
              <BarChart3 className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Open Balance</p>
              <p className={`text-2xl font-bold ${totals.openBalance > 0 ? "text-destructive" : "text-emerald-600"}`}>
                ${totals.openBalance.toFixed(2)}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Breakdown table */}
      <Card className="shadow-md border rounded-xl overflow-hidden">
        <CardHeader className="p-5 border-b bg-muted/50">
          <CardTitle className="text-base flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            Breakdown by Account Type
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {rows.length === 0 ? (
            <p className="p-6 text-center text-muted-foreground">No ledger entries found.</p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/30">
                  <TableHead className="font-semibold">Account Type</TableHead>
                  <TableHead className="text-center font-semibold">Entries</TableHead>
                  <TableHead className="text-right font-semibold">Charges</TableHead>
                  <TableHead className="text-right font-semibold">Applied Payments</TableHead>
                  <TableHead className="text-right font-semibold">Open Balance</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((r) => (
                  <TableRow key={r.type}>
                    <TableCell className="font-medium">
                      <Badge variant="outline" className="text-xs">
                        {r.label}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-center text-muted-foreground">{r.count}</TableCell>
                    <TableCell className="text-right font-mono">
                      ${r.charges.toFixed(2)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-emerald-600">
                      {r.appliedPayments > 0 ? `-$${r.appliedPayments.toFixed(2)}` : "—"}
                    </TableCell>
                    <TableCell className={`text-right font-mono font-semibold ${r.openBalance > 0 ? "text-destructive" : "text-emerald-600"}`}>
                      ${r.openBalance.toFixed(2)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
              <TableFooter>
                <TableRow className="bg-muted/50 font-bold">
                  <TableCell>Total</TableCell>
                  <TableCell className="text-center">{totals.count}</TableCell>
                  <TableCell className="text-right font-mono">${totals.charges.toFixed(2)}</TableCell>
                  <TableCell className="text-right font-mono text-emerald-600">
                    -${totals.appliedPayments.toFixed(2)}
                  </TableCell>
                  <TableCell className={`text-right font-mono ${totals.openBalance > 0 ? "text-destructive" : "text-emerald-600"}`}>
                    ${totals.openBalance.toFixed(2)}
                  </TableCell>
                </TableRow>
              </TableFooter>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
