import { createFileRoute } from "@tanstack/react-router";
import { toast } from "sonner";

import { ListPage } from "@/components/app/ListPage";
import { formatDate } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import type { TableColumn } from "@/components/table/DataTable";
import type { GridColumn } from "@/components/grid/types";
import { validators } from "@/components/grid/types";
import { Button } from "@/components/ui/button";
import { documents } from "@/data/mock";
import type { DocumentRow } from "@/data/types";
import { daysUntil } from "@/lib/ops";

export const Route = createFileRoute("/documents")({
  head: () => ({
    meta: [
      { title: "Documents | KareVoyage Operations" },
      { name: "description", content: "Verification queue for passports, visas and travel documents with expiry tracking." },
      { property: "og:title", content: "Documents | KareVoyage Operations" },
      { property: "og:description", content: "Keep every traveller document verified and valid." },
    ],
  }),
  component: DocumentsPage,
});

const gridColumns: GridColumn<DocumentRow>[] = [
  { key: "id", header: "ID", width: 100, editable: false, frozen: true },
  { key: "guest", header: "Guest", width: 170, validate: validators.required("Guest") },
  { key: "trip", header: "Trip", width: 140 },
  { key: "type", header: "Type", width: 140 },
  { key: "name", header: "File", width: 200 },
  { key: "uploadedDate", header: "Uploaded", width: 120, type: "date", validate: validators.date },
  { key: "expiry", header: "Expiry", width: 120, type: "date", validate: validators.date },
  { key: "status", header: "Status", width: 140, type: "status" },
  { key: "verification", header: "Verified by", width: 150 },
  { key: "notes", header: "Notes", width: 200 },
];

/** Lower is more urgent — drives the default queue order. */
const urgency = (d: DocumentRow) =>
  d.status === "Expired" ? 0 : d.status === "Rejected" ? 1 : d.status === "Expiring Soon" ? 2 : d.status === "Pending" || d.status === "Uploaded" ? 2.5 : 3;

const queue = [...documents].sort((a, b) => urgency(a) - urgency(b) || a.expiry.localeCompare(b.expiry));

function DocumentsPage() {
  const columns: TableColumn<DocumentRow>[] = [

    {
      key: "document",
      header: "Document",
      sortValue: (d) => d.type,
      cell: (d) => (
        <div>
          <p className="font-medium">{d.type}</p>
          <p className="text-xs text-muted-foreground">{d.guest} · {d.trip}</p>
        </div>
      ),
    },
    { key: "uploaded", header: "Uploaded", responsive: "hidden lg:table-cell", sortValue: (d) => d.uploadedDate, cell: (d) => formatDate(d.uploadedDate) },
    {
      key: "expiry",
      header: "Expiry",
      sortValue: (d) => d.expiry,
      cell: (d) => {
        const days = daysUntil(d.expiry);
        return (
          <div>
            <p className="text-sm">{formatDate(d.expiry)}</p>
            <p className="text-xs text-muted-foreground">{days < 0 ? `${Math.abs(days)} days ago` : `in ${days} days`}</p>
          </div>
        );
      },
    },
    { key: "verified", header: "Verified by", responsive: "hidden xl:table-cell", cell: (d) => d.verification },
    { key: "status", header: "Status", sortValue: (d) => d.status, cell: (d) => <StatusPill value={d.status} /> },
  ];

  const pending = documents.filter((d) => d.status === "Pending" || d.status === "Uploaded").length;
  const expiring = documents.filter((d) => d.status === "Expiring Soon").length;
  const expired = documents.filter((d) => d.status === "Expired").length;

  return (
    <ListPage
      title="Documents"
      description="The verification queue — every passport, visa and travel document."
      countLabel={(n) => `${n} documents`}
      searchPlaceholder="Search guest, trip, document type…"
      actions={<Button onClick={() => toast.info("Upload dialog opens here.")}>Upload document</Button>}
      above={
        <div className="grid gap-4 sm:grid-cols-3">
          {[
            { label: "Awaiting verification", value: pending, tone: "text-warning-foreground" },
            { label: "Expiring soon", value: expiring, tone: "text-warning-foreground" },
            { label: "Expired", value: expired, tone: "text-destructive" },
          ].map((s) => (
            <div key={s.label} className="rounded-xl border border-border bg-surface px-5 py-4">
              <p className="kv-eyebrow">{s.label}</p>
              <p className={`mt-2 font-display text-[26px] leading-none ${s.tone}`}>{s.value}</p>
            </div>
          ))}
        </div>
      }
      rows={queue}
      columns={columns}
      getId={(d) => d.id}
      searchText={(d) => `${d.guest} ${d.trip} ${d.type} ${d.name}`}
      quickFilters={[
        { key: "queue", label: "Needs action", test: (d) => urgency(d) < 3 },
        { key: "expired", label: "Expired", test: (d) => d.status === "Expired" },
        { key: "expiring", label: "Expiring soon", test: (d) => d.status === "Expiring Soon" },
        { key: "pending", label: "Awaiting verification", test: (d) => d.status === "Pending" || d.status === "Uploaded" },
        { key: "all", label: "All documents", test: () => true },
      ]}
      filters={[
        { key: "status", label: "Status", get: (d) => d.status },
        { key: "type", label: "Type", get: (d) => d.type },
      ]}

      rowActions={[
        { label: "Verify", onSelect: (d) => toast.success(`${d.type} for ${d.guest} verified.`) },
        { label: "Reject", onSelect: (d) => toast.error(`${d.type} for ${d.guest} rejected.`), destructive: true },
      ]}
      bulkBar={(ids, clear) => (
        <>
          <Button size="sm" variant="outline" onClick={() => toast.success(`${ids.length} documents verified.`)}>Verify selected</Button>
          <Button size="sm" variant="ghost" onClick={clear}>Clear</Button>
        </>
      )}
      gridColumns={gridColumns}
      gridModule="Documents"
      emptyTitle="No documents"
      emptyMessage="Uploaded traveller documents will appear here."
    />
  );
}
