import { useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { EyeOff, Landmark, Link2, Unlink } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { Pill } from "@/components/ledger/StatusBadge";
import { ConfidenceIndicator } from "@/components/ledger/ConfidenceIndicator";
import { eur, useLedger } from "@/lib/ledger-store";
import type { BankStatus } from "@/lib/ledger-types";

export const Route = createFileRoute("/firm/bank")({
  head: () => ({
    meta: [
      { title: "Bank matching — Abdelouhab" },
      { name: "description", content: "Match bank transactions with invoices and bookkeeping entries." },
      { property: "og:title", content: "Bank matching — Abdelouhab" },
      { property: "og:description", content: "Review AI-suggested matches for incoming and outgoing payments." },
    ],
  }),
  component: BankPage,
});

const TONE: Record<BankStatus, "neutral" | "green" | "amber" | "danger"> = {
  Unmatched: "neutral",
  Suggested: "amber",
  Matched: "green",
  Partial: "amber",
  Ignored: "neutral",
};

function BankPage() {
  const { transactions, clientName, getInvoice, setTxStatus } = useLedger();
  const [hideIgnored, setHideIgnored] = useState(false);
  const rows = transactions.filter((t) => !hideIgnored || t.status !== "Ignored");

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Workspace"
        title="Bank matching"
        subtitle="Match bank transactions with invoices and bookkeeping entries."
        actions={
          <Button variant="outline" aria-pressed={hideIgnored} onClick={() => setHideIgnored((v) => !v)}>
            <EyeOff size={16} /> {hideIgnored ? "Show ignored" : "Hide ignored"}
          </Button>
        }
      />

      <SectionCard>
        {rows.length === 0 ? (
          <EmptyState
            icon={Landmark}
            title="No bank matches"
            description="No transactions need attention."
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[1040px] text-[13.5px]">
              <thead className="border-b border-border bg-muted/50 text-[11.5px] tracking-wide text-muted-foreground uppercase">
                <tr>
                  <th className="px-5 py-3 text-left font-semibold">Date</th>
                  <th className="px-3 py-3 text-left font-semibold">Description</th>
                  <th className="px-3 py-3 text-left font-semibold">Client</th>
                  <th className="px-3 py-3 text-right font-semibold">Amount</th>
                  <th className="px-3 py-3 text-left font-semibold">Suggested invoice</th>
                  <th className="px-3 py-3 text-left font-semibold">Confidence</th>
                  <th className="px-3 py-3 text-left font-semibold">Status</th>
                  <th className="px-5 py-3 text-right font-semibold">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {rows.map((t) => {
                  const suggested = t.suggestedInvoiceId ? getInvoice(t.suggestedInvoiceId) : undefined;
                  return (
                    <tr key={t.id} className="transition-colors hover:bg-muted/50">
                      <td className="px-5 py-3 text-muted-foreground">{t.date}</td>
                      <td className="px-3 py-3">
                        <p className="font-medium">{t.description}</p>
                        {t.note ? (
                          <span className="mt-1 inline-flex text-[11.5px] text-attention">{t.note}</span>
                        ) : null}
                      </td>
                      <td className="px-3 py-3 text-muted-foreground">{clientName(t.clientId)}</td>
                      <td className="num px-3 py-3 text-right font-medium">{eur(t.amount)}</td>
                      <td className="px-3 py-3">
                        {suggested ? (
                          <Link
                            to="/firm/invoices/$id"
                            params={{ id: suggested.id }}
                            className="text-primary hover:underline"
                          >
                            {suggested.number}
                          </Link>
                        ) : (
                          <span className="text-muted-foreground">—</span>
                        )}
                      </td>
                      <td className="px-3 py-3">
                        {t.confidence ? (
                          <ConfidenceIndicator value={t.confidence} compact />
                        ) : (
                          <span className="text-muted-foreground">—</span>
                        )}
                      </td>
                      <td className="px-3 py-3">
                        <Pill tone={TONE[t.status]}>{t.status}</Pill>
                      </td>
                      <td className="px-5 py-3">
                        <div className="flex justify-end gap-1.5">
                          {t.status !== "Matched" ? (
                            <Button size="sm" onClick={() => setTxStatus(t.id, "Matched")}>
                              <Link2 size={15} /> Match
                            </Button>
                          ) : (
                            <Button size="sm" variant="outline" onClick={() => setTxStatus(t.id, "Unmatched")}>
                              <Unlink size={15} /> Unmatch
                            </Button>
                          )}
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setTxStatus(t.id, "Ignored")}
                            disabled={t.status === "Ignored"}
                          >
                            Ignore
                          </Button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </div>
  );
}
