import { useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { EmptyState, Money, StatusBadge } from "@/components/ui-kit";
import { formatDate, formatMoney } from "@/lib/format";
import { listAccountLedgerLines, type AccountLedgerLine } from "@/lib/erp";

/**
 * Drilldown behind an "As of" balance: every posted General Ledger line that
 * makes up the figure, with a running balance so the total is auditable.
 */
export function AccountLedgerDrilldown({
  open,
  onOpenChange,
  accountId,
  label,
  asOf,
  normalBalance = "debit",
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  accountId: string | null;
  label: string;
  asOf: string;
  normalBalance?: string;
}) {
  const { data: lines = [], isLoading } = useQuery({
    queryKey: ["account-ledger-lines", accountId, asOf],
    queryFn: () => listAccountLedgerLines(accountId as string, asOf),
    enabled: open && !!accountId,
  });

  const rows = lines as AccountLedgerLine[];
  const sign = normalBalance === "credit" ? -1 : 1;
  let running = 0;
  const withRunning = rows.map((l) => {
    running += sign * (Number(l.debit) - Number(l.credit));
    return { ...l, running };
  });
  const totalDebit = rows.reduce((s, l) => s + Number(l.debit), 0);
  const totalCredit = rows.reduce((s, l) => s + Number(l.credit), 0);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[88vh] overflow-y-auto sm:max-w-3xl">
        <DialogHeader>
          <DialogTitle>Ledger lines — {label}</DialogTitle>
          <DialogDescription>
            Posted entries dated on or before {formatDate(asOf)}. The running balance ends on the
            same figure shown in the “As of” preview.
          </DialogDescription>
        </DialogHeader>

        {isLoading ? (
          <p className="py-6 text-center text-sm text-muted-foreground">Loading ledger lines…</p>
        ) : rows.length === 0 ? (
          <EmptyState
            title="No ledger activity"
            description="Nothing has been posted to this account up to this date, so the balance is zero."
          />
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Date</TableHead>
                  <TableHead>Entry</TableHead>
                  <TableHead>Source</TableHead>
                  <TableHead>Description</TableHead>
                  <TableHead className="text-right">Debit</TableHead>
                  <TableHead className="text-right">Credit</TableHead>
                  <TableHead className="text-right">Balance</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {withRunning.map((l) => (
                  <TableRow key={l.line_id}>
                    <TableCell className="whitespace-nowrap">{formatDate(l.entry_date)}</TableCell>
                    <TableCell className="num">{l.entry_number}</TableCell>
                    <TableCell>
                      <StatusBadge status={l.source_type} />
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {l.description || l.memo || "—"}
                    </TableCell>
                    <TableCell className="text-right">
                      <Money value={Number(l.debit)} />
                    </TableCell>
                    <TableCell className="text-right">
                      <Money value={Number(l.credit)} />
                    </TableCell>
                    <TableCell className="num text-right font-medium">
                      {formatMoney(l.running)}
                    </TableCell>
                  </TableRow>
                ))}
                <TableRow className="font-semibold">
                  <TableCell colSpan={4}>Total ({rows.length} lines)</TableCell>
                  <TableCell className="num text-right">{formatMoney(totalDebit)}</TableCell>
                  <TableCell className="num text-right">{formatMoney(totalCredit)}</TableCell>
                  <TableCell className="num text-right">{formatMoney(running)}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
