import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { FileSpreadsheet, Trash2, ChevronRight, Upload, Inbox } from "lucide-react";
import { getHistory, deleteResult, type StoredSummary } from "@/lib/history";
import { SeverityBadge } from "@/components/severity-badge";

export const Route = createFileRoute("/history")({
  component: HistoryPage,
});

function HistoryPage() {
  const [history, setHistory] = useState<StoredSummary[]>([]);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    setHistory(getHistory());
    setLoaded(true);
  }, []);

  const remove = (id: string) => {
    deleteResult(id);
    setHistory(getHistory());
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold text-foreground sm:text-3xl">History</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Past analyses saved on this device.
          </p>
        </div>
        <Link
          to="/upload"
          className="inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)]"
        >
          <Upload className="h-4 w-4" />
          <span className="hidden sm:inline">Upload</span>
        </Link>
      </div>

      {loaded && history.length === 0 && (
        <div className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-border bg-card/50 p-12 text-center">
          <span className="flex h-12 w-12 items-center justify-center rounded-full bg-secondary text-muted-foreground">
            <Inbox className="h-6 w-6" />
          </span>
          <h2 className="font-display text-lg font-semibold text-foreground">No analyses yet</h2>
          <p className="max-w-sm text-sm text-muted-foreground">
            Upload a CSV or Excel file to run your first anomaly detection.
          </p>
          <Link
            to="/upload"
            className="mt-1 inline-flex items-center gap-2 rounded-xl bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground"
          >
            <Upload className="h-4 w-4" />
            Upload data
          </Link>
        </div>
      )}

      <div className="space-y-2">
        {history.map((h) => (
          <div
            key={h.id}
            className="group flex items-center gap-3 rounded-xl border border-border bg-card p-4 shadow-[var(--shadow-panel)] transition-colors hover:border-primary/40"
          >
            <Link
              to="/analysis/$id"
              params={{ id: h.id }}
              className="flex min-w-0 flex-1 items-center gap-3"
            >
              <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-secondary text-secondary-foreground">
                <FileSpreadsheet className="h-5 w-5" />
              </span>
              <div className="min-w-0 flex-1">
                <p className="truncate font-medium text-foreground">{h.filename}</p>
                <p className="text-xs text-muted-foreground">
                  {h.totalRows.toLocaleString()} rows ·{" "}
                  {new Date(h.uploadDate).toLocaleString()}
                </p>
              </div>
              <div className="hidden text-right sm:block">
                <p className="font-display text-lg font-bold tabular-nums text-foreground">
                  {h.anomalyCount.toLocaleString()}
                </p>
                <p className="text-[11px] text-muted-foreground">anomalies</p>
              </div>
              <SeverityBadge
                severity={h.criticalCount > 0 ? "critical" : h.anomalyCount > 0 ? "warning" : "ok"}
              />
              <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
            </Link>
            <button
              onClick={() => remove(h.id)}
              aria-label={`Delete ${h.filename}`}
              className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}
