import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import {
  Upload,
  Activity,
  Waves,
  BatteryLow,
  ShieldCheck,
  ArrowRight,
  FileSpreadsheet,
  Zap,
  ChevronRight,
} from "lucide-react";
import { getHistory, type StoredSummary } from "@/lib/history";
import { StatCard } from "@/components/stat-card";
import { SeverityBadge } from "@/components/severity-badge";

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

const FEATURES = [
  {
    icon: FileSpreadsheet,
    title: "Smart Upload",
    body: "Drop in .csv or .xlsx meter exports — no reformatting needed.",
  },
  {
    icon: Activity,
    title: "Auto header mapping",
    body: '"Current Ph-A", "Arus R", "Ir" — all matched to the right phase automatically.',
  },
  {
    icon: Waves,
    title: "Unbalance detection",
    body: "Flags phase-current imbalance against your configured threshold.",
  },
  {
    icon: BatteryLow,
    title: "Under-voltage alerts",
    body: "Detects sags below the reference voltage, color-coded by severity.",
  },
];

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

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

  const totals = history.reduce(
    (acc, h) => {
      acc.rows += h.totalRows;
      acc.anomalies += h.anomalyCount;
      acc.critical += h.criticalCount;
      return acc;
    },
    { rows: 0, anomalies: 0, critical: 0 },
  );

  return (
    <div className="space-y-8">
      {/* Hero */}
      <section className="grid-blueprint relative overflow-hidden rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-panel)] sm:p-10">
        <div className="relative max-w-2xl">
          <span className="inline-flex items-center gap-1.5 rounded-full border border-primary/30 bg-primary/10 px-3 py-1 text-xs font-semibold text-primary">
            <Zap className="h-3.5 w-3.5" />
            Field-ready anomaly detection
          </span>
          <h1 className="mt-4 font-display text-3xl font-bold leading-tight text-foreground sm:text-5xl">
            Find electrical anomalies in seconds, not hours.
          </h1>
          <p className="mt-4 text-base text-muted-foreground sm:text-lg">
            Upload thousands of meter readings and instantly surface{" "}
            <span className="font-semibold text-foreground">unbalance current</span> and{" "}
            <span className="font-semibold text-foreground">under voltage</span> events — visualized
            per phase, ready to export.
          </p>
          <div className="mt-6 flex flex-wrap gap-3">
            <Link
              to="/upload"
              className="inline-flex items-center gap-2 rounded-xl bg-primary px-5 py-3 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-transform hover:scale-[1.02]"
            >
              <Upload className="h-4 w-4" />
              Upload data
            </Link>
            <Link
              to="/history"
              className="inline-flex items-center gap-2 rounded-xl border border-border bg-background px-5 py-3 text-sm font-semibold text-foreground transition-colors hover:bg-secondary"
            >
              View history
              <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </div>
      </section>

      {/* Aggregate stats */}
      {loaded && history.length > 0 && (
        <section className="grid grid-cols-2 gap-3 lg:grid-cols-4">
          <StatCard
            label="Files analyzed"
            value={history.length}
            icon={<FileSpreadsheet className="h-5 w-5" />}
            tone="primary"
          />
          <StatCard
            label="Rows processed"
            value={totals.rows.toLocaleString()}
            icon={<Activity className="h-5 w-5" />}
          />
          <StatCard
            label="Anomalies found"
            value={totals.anomalies.toLocaleString()}
            icon={<Waves className="h-5 w-5" />}
            tone="warning"
          />
          <StatCard
            label="Critical events"
            value={totals.critical.toLocaleString()}
            icon={<BatteryLow className="h-5 w-5" />}
            tone="critical"
          />
        </section>
      )}

      {/* Recent analyses */}
      {loaded && history.length > 0 && (
        <section>
          <div className="mb-3 flex items-center justify-between">
            <h2 className="font-display text-xl font-bold text-foreground">Recent analyses</h2>
            <Link to="/history" className="text-sm font-medium text-primary hover:underline">
              See all
            </Link>
          </div>
          <div className="space-y-2">
            {history.slice(0, 4).map((h) => (
              <Link
                key={h.id}
                to="/analysis/$id"
                params={{ id: h.id }}
                className="flex items-center gap-3 rounded-xl border border-border bg-card p-4 shadow-[var(--shadow-panel)] transition-colors hover:border-primary/40"
              >
                <span className="flex h-10 w-10 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).toLocaleDateString()}
                  </p>
                </div>
                <SeverityBadge
                  severity={h.criticalCount > 0 ? "critical" : h.anomalyCount > 0 ? "warning" : "ok"}
                  className="hidden sm:inline-flex"
                />
                <span className="text-sm font-semibold tabular-nums text-foreground">
                  {h.anomalyCount}
                  <span className="ml-1 text-xs font-normal text-muted-foreground">anomalies</span>
                </span>
                <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
              </Link>
            ))}
          </div>
        </section>
      )}

      {/* Features (shown prominently for first-time users) */}
      <section>
        {loaded && history.length === 0 && (
          <h2 className="mb-4 font-display text-xl font-bold text-foreground">How it works</h2>
        )}
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {FEATURES.map((f) => (
            <div
              key={f.title}
              className="rounded-xl border border-border bg-card p-5 shadow-[var(--shadow-panel)]"
            >
              <span className="flex h-11 w-11 items-center justify-center rounded-lg bg-primary/10 text-primary">
                <f.icon className="h-5 w-5" />
              </span>
              <h3 className="mt-3 font-display font-semibold text-foreground">{f.title}</h3>
              <p className="mt-1 text-sm text-muted-foreground">{f.body}</p>
            </div>
          ))}
        </div>
      </section>

      {loaded && history.length === 0 && (
        <section className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-border bg-card/50 p-8 text-center">
          <span className="flex h-12 w-12 items-center justify-center rounded-full bg-success/10 text-success">
            <ShieldCheck className="h-6 w-6" />
          </span>
          <h3 className="font-display text-lg font-semibold text-foreground">
            Everything runs in your browser
          </h3>
          <p className="max-w-md text-sm text-muted-foreground">
            Your files are analyzed locally and saved to this device — perfect for spotty field
            connectivity. Upload a file to get started.
          </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 your first file
          </Link>
        </section>
      )}
    </div>
  );
}
