import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
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 { PasteImportDialog } from "@/components/grid/PasteImportDialog";
import { Button } from "@/components/ui/button";
import { importRuns } from "@/data/mock";
import type { ImportRun } from "@/data/types";

export const Route = createFileRoute("/imports")({
  head: () => ({
    meta: [
      { title: "Import centre | KareVoyage Operations" },
      { name: "description", content: "Paste data from Excel, map columns, validate and import into any module." },
      { property: "og:title", content: "Import centre | KareVoyage Operations" },
      { property: "og:description", content: "Excel-first bulk imports with validation." },
    ],
  }),
  component: ImportsPage,
});

const MODULES = ["Guests", "Tours", "Trips", "Itinerary", "Hotels", "Flights", "Transport", "Payments", "Documents"];

const IMPORT_COLUMNS: GridColumn[] = [
  { key: "reference", header: "Reference", width: 150, validate: validators.required("Reference") },
  { key: "name", header: "Name", width: 180, validate: validators.required("Name") },
  { key: "email", header: "Email", width: 220, validate: validators.email },
  { key: "mobile", header: "Mobile", width: 150, validate: validators.phone },
  { key: "date", header: "Date", width: 130, type: "date", validate: validators.date },
  { key: "amount", header: "Amount", width: 130, type: "money", align: "right" },
  { key: "notes", header: "Notes", width: 200 },
];

const gridColumns: GridColumn<ImportRun>[] = [
  { key: "id", header: "Run ID", width: 120, editable: false, frozen: true },
  { key: "module", header: "Module", width: 150 },
  { key: "date", header: "Date", width: 130, type: "date", validate: validators.date },
  { key: "rows", header: "Rows", width: 90, type: "number", align: "right" },
  { key: "success", header: "Imported", width: 100, type: "number", align: "right" },
  { key: "errors", header: "Errors", width: 90, type: "number", align: "right" },
  { key: "importedBy", header: "Imported by", width: 150 },
  { key: "status", header: "Status", width: 170, type: "status" },
];

function ImportsPage() {
  const [open, setOpen] = useState(false);
  const [module, setModule] = useState("Guests");

  const columns: TableColumn<ImportRun>[] = [
    {
      key: "run",
      header: "Import run",
      sortValue: (r) => r.date,
      cell: (r) => (
        <div>
          <p className="font-medium">{r.module}</p>
          <p className="text-xs text-muted-foreground">{r.id} · {r.importedBy}</p>
        </div>
      ),
    },
    { key: "date", header: "Date", sortValue: (r) => r.date, cell: (r) => formatDate(r.date) },
    { key: "rows", header: "Rows", align: "right", sortValue: (r) => r.rows, cell: (r) => r.rows },
    { key: "success", header: "Imported", align: "right", sortValue: (r) => r.success, cell: (r) => <span className="text-success">{r.success}</span> },
    { key: "errors", header: "Errors", align: "right", sortValue: (r) => r.errors, cell: (r) => <span className={r.errors ? "text-destructive" : ""}>{r.errors}</span> },
    { key: "status", header: "Status", sortValue: (r) => r.status, cell: (r) => <StatusPill value={r.status} /> },
  ];

  return (
    <>
      <ListPage
        title="Import centre"
        description="Copy from Excel, paste here, map the columns, fix what's flagged, import."
        countLabel={(n) => `${n} import runs`}
        searchPlaceholder="Search runs, modules, people…"
        actions={<Button onClick={() => setOpen(true)}>Paste from Excel</Button>}
        above={
          <div className="rounded-xl border border-border bg-surface p-5">
            <p className="kv-eyebrow mb-3">Start an import</p>
            <div className="flex flex-wrap gap-2">
              {MODULES.map((m) => (
                <Button
                  key={m}
                  variant={module === m ? "default" : "outline"}
                  size="sm"
                  onClick={() => {
                    setModule(m);
                    setOpen(true);
                  }}
                >
                  {m}
                </Button>
              ))}
            </div>
            <p className="mt-4 text-xs text-muted-foreground">
              Every import runs the same four steps: paste → map columns → validate → import. Invalid cells are highlighted so
              they can be corrected before anything is saved.
            </p>
          </div>
        }
        rows={importRuns}
        columns={columns}
        getId={(r) => r.id}
        searchText={(r) => `${r.id} ${r.module} ${r.importedBy}`}
        filters={[
          { key: "module", label: "Module", get: (r) => r.module },
          { key: "status", label: "Status", get: (r) => r.status },
        ]}
        rowActions={[{ label: "Download error report", onSelect: () => toast.success("Error report downloaded.") }]}
        gridColumns={gridColumns}
        gridModule="Import Runs"
        emptyTitle="No imports yet"
        emptyMessage="Paste your first spreadsheet to get started."
      />
      <PasteImportDialog
        open={open}
        onOpenChange={setOpen}
        moduleName={module}
        columns={IMPORT_COLUMNS}
        onImport={(rows) => toast.success(`${rows.length} rows ready to import into ${module}.`)}
      />
    </>
  );
}
