import { useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ChevronDown, ChevronUp, BarChart3 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

interface BalanceRow {
  balance: number;
  assessments: number;
  lateFees: number;
  interest: number;
  adminFees: number;
  legalFees: number;
  violations: number;
  bankFees: number;
  payments: number;
  agingDays: number;
}

interface ARAgingSummaryProps {
  rows: BalanceRow[];
  associationFilter: string;
}

const AGING_BUCKETS = [
  { key: "0-30", label: "0–30 Days", min: 0, max: 30 },
  { key: "31-60", label: "31–60 Days", min: 31, max: 60 },
  { key: "61-90", label: "61–90 Days", min: 61, max: 90 },
  { key: "91+", label: "91+ Days", min: 91, max: Infinity },
] as const;

const FEE_CATEGORIES = [
  { key: "assessments", label: "Assessments" },
  { key: "lateFees", label: "Late Fees" },
  { key: "interest", label: "Interest" },
  { key: "adminFees", label: "Admin Fees" },
  { key: "legalFees", label: "Legal Fees" },
  { key: "violations", label: "Violations" },
  { key: "bankFees", label: "Bank Fees" },
] as const;

const fmt = (n: number) =>
  `$${Math.abs(n).toLocaleString(undefined, { minimumFractionDigits: 2 })}`;

export default function ARAgingSummary({ rows }: ARAgingSummaryProps) {
  const [expanded, setExpanded] = useState(false);

  const agingData = useMemo(() => {
    const buckets = AGING_BUCKETS.map((b) => {
      const bucketRows = rows.filter(
        (r) => r.agingDays >= b.min && r.agingDays <= b.max
      );
      const totals: Record<string, number> = {};
      FEE_CATEGORIES.forEach((cat) => {
        totals[cat.key] = bucketRows.reduce(
          (sum, r) => sum + (r[cat.key as keyof BalanceRow] as number),
          0
        );
      });
      totals.payments = bucketRows.reduce((sum, r) => sum + r.payments, 0);
      totals.balance = bucketRows.reduce((sum, r) => sum + r.balance, 0);
      totals.count = bucketRows.length;
      return { ...b, totals };
    });

    // Grand totals
    const grand: Record<string, number> = {};
    FEE_CATEGORIES.forEach((cat) => {
      grand[cat.key] = buckets.reduce((s, b) => s + b.totals[cat.key], 0);
    });
    grand.payments = buckets.reduce((s, b) => s + b.totals.payments, 0);
    grand.balance = buckets.reduce((s, b) => s + b.totals.balance, 0);
    grand.count = buckets.reduce((s, b) => s + b.totals.count, 0);

    return { buckets, grand };
  }, [rows]);

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base font-semibold flex items-center gap-2">
            <BarChart3 className="h-4 w-4 text-primary" />
            A/R Aging Report
          </CardTitle>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setExpanded(!expanded)}
            className="gap-1 text-muted-foreground"
          >
            {expanded ? (
              <>
                Collapse <ChevronUp className="h-4 w-4" />
              </>
            ) : (
              <>
                Expand <ChevronDown className="h-4 w-4" />
              </>
            )}
          </Button>
        </div>
      </CardHeader>

      {/* Always show compact summary row */}
      <CardContent className="pt-0">
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-2">
          {agingData.buckets.map((bucket) => (
            <div
              key={bucket.key}
              className="rounded-lg border bg-muted/30 px-3 py-2"
            >
              <p className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">
                {bucket.label}
              </p>
              <p className="text-lg font-bold text-foreground">
                {fmt(bucket.totals.balance)}
              </p>
              <p className="text-[11px] text-muted-foreground">
                {bucket.totals.count} account{bucket.totals.count !== 1 ? "s" : ""}
              </p>
            </div>
          ))}
        </div>

        {/* Expanded detailed breakdown */}
        {expanded && (
          <div className="overflow-x-auto mt-4 rounded-lg border">
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/50">
                  <TableHead className="font-semibold">Category</TableHead>
                  {AGING_BUCKETS.map((b) => (
                    <TableHead key={b.key} className="text-right font-semibold">
                      {b.label}
                    </TableHead>
                  ))}
                  <TableHead className="text-right font-semibold">Total</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {FEE_CATEGORIES.map((cat) => (
                  <TableRow key={cat.key}>
                    <TableCell className="font-medium">{cat.label}</TableCell>
                    {agingData.buckets.map((bucket) => (
                      <TableCell
                        key={bucket.key}
                        className={cn(
                          "text-right tabular-nums",
                          bucket.totals[cat.key] > 0 && "text-foreground",
                          bucket.totals[cat.key] === 0 && "text-muted-foreground"
                        )}
                      >
                        {fmt(bucket.totals[cat.key])}
                      </TableCell>
                    ))}
                    <TableCell className="text-right tabular-nums font-semibold">
                      {fmt(agingData.grand[cat.key])}
                    </TableCell>
                  </TableRow>
                ))}
                {/* Payments row */}
                <TableRow className="border-t">
                  <TableCell className="font-medium text-primary">
                    Payments Applied
                  </TableCell>
                  {agingData.buckets.map((bucket) => (
                    <TableCell
                      key={bucket.key}
                      className="text-right tabular-nums text-primary"
                    >
                      {fmt(bucket.totals.payments)}
                    </TableCell>
                  ))}
                  <TableCell className="text-right tabular-nums font-semibold text-primary">
                    {fmt(agingData.grand.payments)}
                  </TableCell>
                </TableRow>
                {/* Balance Due row */}
                <TableRow className="bg-muted/50 border-t-2 font-bold">
                  <TableCell className="text-destructive">Balance Due</TableCell>
                  {agingData.buckets.map((bucket) => (
                    <TableCell
                      key={bucket.key}
                      className="text-right tabular-nums text-destructive"
                    >
                      {fmt(bucket.totals.balance)}
                    </TableCell>
                  ))}
                  <TableCell className="text-right tabular-nums text-destructive">
                    {fmt(agingData.grand.balance)}
                  </TableCell>
                </TableRow>
                {/* Accounts count row */}
                <TableRow>
                  <TableCell className="text-muted-foreground text-xs">
                    # of Accounts
                  </TableCell>
                  {agingData.buckets.map((bucket) => (
                    <TableCell
                      key={bucket.key}
                      className="text-right text-xs text-muted-foreground"
                    >
                      {bucket.totals.count}
                    </TableCell>
                  ))}
                  <TableCell className="text-right text-xs font-medium text-muted-foreground">
                    {agingData.grand.count}
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
