import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { accounting } from "@/lib/accountingClient";
import { useCompanyId } from "./lib/useCompanyId";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { money, fmtDate } from "./lib/format";
import { Landmark, CreditCard, Loader2 } from "lucide-react";

export default function AccountingReconciliationPage() {
  const { companyId, loading: companyLoading, error: companyError, associationId } = useCompanyId();
  const cid = companyId ?? "";
  const cur = "USD";

  const { data: accounts = [] } = useQuery({
    queryKey: ["recon-accounts", cid],
    enabled: !!cid,
    queryFn: async () =>
      (
        await accounting
          .from("accounts")
          .select("*")
          .eq("company_id", cid)
          .or("is_bank.eq.true,subtype.eq.credit_card")
          .order("name")
      ).data ?? [],
  });

  const { data: lastRecs = [] } = useQuery({
    queryKey: ["recon-last", cid],
    enabled: !!cid,
    queryFn: async () =>
      (
        await accounting
          .from("reconciliations")
          .select("account_id, statement_end_date, statement_balance, status, completed_at")
          .eq("company_id", cid)
          .eq("status", "completed")
          .order("statement_end_date", { ascending: false })
      ).data ?? [],
  });

  const lastByAcc = new Map<string, any>();
  for (const r of lastRecs as any[]) if (!lastByAcc.has(r.account_id)) lastByAcc.set(r.account_id, r);

  const isStale = (d?: string | null) => {
    if (!d) return true;
    return (Date.now() - new Date(d).getTime()) / 86400000 > 30;
  };

  const subtypeLabel = (a: any) =>
    a.subtype === "credit_card"
      ? "Credit Card"
      : a.subtype === "savings"
        ? "Savings"
        : a.subtype === "checking"
          ? "Checking"
          : a.is_bank
            ? "Bank"
            : "Account";

  if (!associationId) return <p className="text-sm text-muted-foreground">Select an association.</p>;
  if (companyLoading) return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
  if (companyError || !companyId) return <p className="text-sm text-muted-foreground text-center py-12">{companyError || "Accounting setup is not ready."}</p>;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Bank Reconciliation</h1>
        <p className="text-sm text-muted-foreground">
          Reconcile your bank and credit card accounts against your statements.
        </p>
      </div>

      {(accounts as any[]).length === 0 && (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            No bank or credit card accounts yet. Add one from Chart of Accounts.
          </CardContent>
        </Card>
      )}

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        {(accounts as any[]).map((acc: any) => {
          const last = lastByAcc.get(acc.id);
          const stale = isStale(last?.statement_end_date);
          const Icon = acc.subtype === "credit_card" ? CreditCard : Landmark;
          return (
            <Card key={acc.id} className="overflow-hidden">
              <CardContent className="p-5 space-y-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex items-center gap-3">
                    <div className="rounded-md bg-primary/10 p-2 text-primary">
                      <Icon className="h-5 w-5" />
                    </div>
                    <div>
                      <div className="font-medium leading-tight">{acc.name}</div>
                      <div className="text-xs text-muted-foreground">{subtypeLabel(acc)}</div>
                    </div>
                  </div>
                  {stale && (
                    <Badge variant="destructive" className="shrink-0">
                      Unreconciled
                    </Badge>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div>
                    <div className="text-muted-foreground text-xs">Last reconciled</div>
                    <div>{last ? fmtDate(last.statement_end_date) : "Never"}</div>
                  </div>
                  <div className="text-right">
                    <div className="text-muted-foreground text-xs">Last balance</div>
                    <div>{last ? money(last.statement_balance, cur) : "—"}</div>
                  </div>
                </div>

                <div className="flex items-center justify-between pt-1">
                  <div className="text-xs text-muted-foreground">
                    Current: <span className="font-medium text-foreground">{money(acc.balance, cur)}</span>
                  </div>
                  <Button asChild size="sm" className="bg-primary hover:bg-primary/90">
                    <Link to={`/dashboard/accounting/reconciliation/${acc.id}`}>
                      Reconcile
                    </Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
