import { useMemo, useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { CheckCheck, ChevronRight, FileStack, Filter, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { EmptyState, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { StatusBadge } from "@/components/ledger/StatusBadge";
import { ConfidenceIndicator } from "@/components/ledger/ConfidenceIndicator";
import { UploadDropzone } from "@/components/ledger/UploadDropzone";
import { eur, useLedger } from "@/lib/ledger-store";
import type { InvoiceStatus } from "@/lib/ledger-types";

const STATUSES: InvoiceStatus[] = [
  "New",
  "AI processed",
  "Needs review",
  "Auto-ready",
  "Approved",
  "Rejected",
  "Synced",
  "Sync failed",
];

export const Route = createFileRoute("/firm/inbox")({
  validateSearch: (search: Record<string, unknown>) => ({
    client: typeof search["client"] === "string" ? (search["client"] as string) : undefined,
  }),
  head: () => ({
    meta: [
      { title: "Document inbox — Abdelouhab" },
      { name: "description", content: "Review, approve and prepare documents for SnelStart." },
      { property: "og:title", content: "Document inbox — Abdelouhab" },
      { property: "og:description", content: "Process uploaded invoices with AI booking suggestions." },
    ],
  }),
  component: InboxPage,
});

function InboxPage() {
  const { client: clientParam } = Route.useSearch();
  const { invoices, clients, clientName, uploadDocument, bulkApprove, bulkNeedsReview } = useLedger();
  const [search, setSearch] = useState("");
  const [status, setStatus] = useState("all");
  const [client, setClient] = useState(clientParam ?? "all");
  const [confidence, setConfidence] = useState("all");
  const [date, setDate] = useState("");
  const [selected, setSelected] = useState<string[]>([]);

  const rows = useMemo(
    () =>
      invoices.filter((i) => {
        const q = search.toLowerCase();
        if (q && !`${i.supplier} ${i.file} ${i.number}`.toLowerCase().includes(q)) return false;
        if (status !== "all" && i.status !== status) return false;
        if (client !== "all" && i.clientId !== client) return false;
        if (date && i.uploadedAt !== date) return false;
        if (confidence === "high" && i.confidence < 85) return false;
        if (confidence === "medium" && (i.confidence < 65 || i.confidence >= 85)) return false;
        if (confidence === "low" && i.confidence >= 65) return false;
        return true;
      }),
    [invoices, search, status, client, confidence, date],
  );

  const allSelected = rows.length > 0 && rows.every((r) => selected.includes(r.id));

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Workspace"
        title="Document inbox"
        subtitle="Review, approve and prepare documents for SnelStart."
        actions={
          <>
            <Button
              variant="outline"
              disabled={selected.length === 0}
              onClick={() => {
                bulkNeedsReview(selected);
                setSelected([]);
              }}
            >
              <Filter size={16} /> Mark needs review
            </Button>
            <Button
              disabled={selected.length === 0}
              onClick={() => {
                bulkApprove(selected);
                setSelected([]);
              }}
            >
              <CheckCheck size={16} /> Bulk approve{selected.length ? ` (${selected.length})` : ""}
            </Button>
          </>
        }
      />

      <UploadDropzone
        onFiles={(names) => names.forEach((n) => uploadDocument(client === "all" ? "c1" : client, n, "Sara"))}
      />

      <SectionCard>
        <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-3">
          <div className="relative">
            <Search
              size={16}
              className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-muted-foreground"
              aria-hidden="true"
            />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search documents"
              aria-label="Search documents"
              className="h-9 w-56 bg-surface pl-8"
            />
          </div>
          <Select value={status} onValueChange={setStatus}>
            <SelectTrigger className="h-9 w-[150px] bg-surface" aria-label="Filter by status">
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All statuses</SelectItem>
              {STATUSES.map((s) => (
                <SelectItem key={s} value={s}>
                  {s}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={client} onValueChange={setClient}>
            <SelectTrigger className="h-9 w-[170px] bg-surface" aria-label="Filter by client">
              <SelectValue placeholder="Client" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All clients</SelectItem>
              {clients.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={confidence} onValueChange={setConfidence}>
            <SelectTrigger className="h-9 w-[150px] bg-surface" aria-label="Filter by confidence">
              <SelectValue placeholder="Confidence" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Any confidence</SelectItem>
              <SelectItem value="high">High (85%+)</SelectItem>
              <SelectItem value="medium">Medium (65–84%)</SelectItem>
              <SelectItem value="low">Low (&lt;65%)</SelectItem>
            </SelectContent>
          </Select>
          <Input
            type="date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            aria-label="Filter by upload date"
            className="h-9 w-[160px] bg-surface"
          />
        </div>

        {rows.length === 0 ? (
          <EmptyState
            icon={FileStack}
            title="No documents found"
            description="No invoices match your current filters."
            action={
              <Button
                variant="outline"
                onClick={() => {
                  setSearch("");
                  setStatus("all");
                  setClient("all");
                  setConfidence("all");
                  setDate("");
                }}
              >
                Clear filters
              </Button>
            }
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[980px] text-[13.5px]">
              <thead className="border-b border-border bg-muted/50 text-[11.5px] tracking-wide text-muted-foreground uppercase">
                <tr>
                  <th className="w-10 px-4 py-3">
                    <Checkbox
                      checked={allSelected}
                      aria-label="Select all documents"
                      onCheckedChange={(v) => setSelected(v ? rows.map((r) => r.id) : [])}
                    />
                  </th>
                  <th className="px-3 py-3 text-left font-semibold">File</th>
                  <th className="px-3 py-3 text-left font-semibold">Client</th>
                  <th className="px-3 py-3 text-left font-semibold">Supplier</th>
                  <th className="px-3 py-3 text-right font-semibold">Amount</th>
                  <th className="px-3 py-3 text-left font-semibold">Uploaded</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="w-10 px-3 py-3" />
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {rows.map((i) => (
                  <tr key={i.id} className="transition-colors hover:bg-muted/50">
                    <td className="px-4 py-3">
                      <Checkbox
                        checked={selected.includes(i.id)}
                        aria-label={`Select ${i.file}`}
                        onCheckedChange={(v) =>
                          setSelected((prev) => (v ? [...prev, i.id] : prev.filter((x) => x !== i.id)))
                        }
                      />
                    </td>
                    <td className="max-w-[220px] truncate px-3 py-3">
                      <Link
                        to="/firm/invoices/$id"
                        params={{ id: i.id }}
                        className="font-medium hover:text-primary"
                      >
                        {i.file}
                      </Link>
                    </td>
                    <td className="px-3 py-3 text-muted-foreground">{clientName(i.clientId)}</td>
                    <td className="px-3 py-3">{i.supplier}</td>
                    <td className="num px-3 py-3 text-right font-medium">{eur(i.total)}</td>
                    <td className="px-3 py-3 text-muted-foreground">{i.uploadedAt}</td>
                    <td className="px-3 py-3">
                      <ConfidenceIndicator value={i.confidence} compact />
                    </td>
                    <td className="px-3 py-3">
                      <StatusBadge status={i.status} />
                    </td>
                    <td className="px-3 py-3">
                      <Link
                        to="/firm/invoices/$id"
                        params={{ id: i.id }}
                        aria-label={`Open ${i.file}`}
                        className="text-muted-foreground hover:text-primary"
                      >
                        <ChevronRight size={16} />
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </div>
  );
}
