"use client";

import Link from "next/link";
import { useMemo } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { TOAST_SAMPLE_2025, getToastTotals } from "@/lib/sag/toast-sample";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { rollupByEntity, toastNameToSlug } from "@/lib/sag/toast-csv";
import type { ToastSalesRow } from "@/lib/sag/types";
import { formatCurrency, formatCurrencyCompact } from "@/lib/utils";

interface SavedImport {
  id: string;
  name: string;
  uploadedAt: string;
  rowCount: number;
  rows: ToastSalesRow[];
}

interface EntityTotals {
  source: "uploaded" | "seed";
  sourceName: string;
  totals: { itemQty: number; netSales: number; grossSales: number; taxAmount: number };
  topEntities: Array<{ entitySlug: string; netSales: number; itemQty: number; toastName: string }>;
}

export function DashboardStats() {
  const [imports] = useLocalStorage<SavedImport[]>("sag.toast.imports", []);
  const [billsCount] = useLocalStorage<unknown[]>("sag.bills", []);

  const data = useMemo<EntityTotals>(() => {
    const latest = imports[0];
    if (latest && latest.rows.length > 0) {
      const rolled = rollupByEntity(latest.rows);
      const totals = rolled.reduce(
        (a, r) => ({
          itemQty: a.itemQty + r.itemQty,
          netSales: a.netSales + r.netSales,
          grossSales: a.grossSales + r.grossSales,
          taxAmount: a.taxAmount + r.taxAmount,
        }),
        { itemQty: 0, netSales: 0, grossSales: 0, taxAmount: 0 }
      );
      const topEntities = [...rolled]
        .sort((a, b) => b.netSales - a.netSales)
        .slice(0, 5)
        .map((r) => ({
          entitySlug: toastNameToSlug(r.salesCategory) ?? r.salesCategory,
          netSales: r.netSales,
          itemQty: r.itemQty,
          toastName: r.salesCategory,
        }));
      return { source: "uploaded", sourceName: latest.name, totals, topEntities };
    }
    return {
      source: "seed",
      sourceName: "2025 partial (seed)",
      totals: getToastTotals(),
      topEntities: [...TOAST_SAMPLE_2025]
        .sort((a, b) => b.netSales - a.netSales)
        .slice(0, 5)
        .map((r) => ({
          entitySlug: r.entitySlug,
          netSales: r.netSales,
          itemQty: r.itemQty,
          toastName: r.toastName,
        })),
    };
  }, [imports]);

  return (
    <>
      <section className="grid gap-4 grid-cols-2 lg:grid-cols-4">
        <MetricCard
          label="Total entities"
          value={String(ALL_ORGANIZATIONS.length)}
          hint="parent + subsidiaries"
          tone="brand"
        />
        <MetricCard
          label="Portfolio net sales"
          value={formatCurrencyCompact(data.totals.netSales)}
          hint={data.source === "uploaded" ? `from ${data.sourceName}` : "Toast 2025 partial (seed)"}
          source={data.source}
          tone="emerald"
        />
        <MetricCard
          label="Items sold"
          value={data.totals.itemQty.toLocaleString()}
          hint="Toast item count"
          tone="amber"
        />
        <MetricCard
          label="Bills tracked"
          value={String(billsCount.length)}
          hint={billsCount.length > 0 ? "open + paid" : "Add bills in /app/finance/bills"}
          placeholder={billsCount.length === 0}
          tone="violet"
        />
      </section>

      <Card>
        <CardContent className="p-6">
          <div className="flex items-center justify-between flex-wrap gap-2 mb-4">
            <div>
              <h2 className="text-base font-semibold">Top entities by sales</h2>
              <p className="text-xs text-muted-foreground">
                {data.source === "uploaded" ? (
                  <>From your upload: <span className="font-medium">{data.sourceName}</span></>
                ) : (
                  <>Seeded 2025 partial. Upload a Toast CSV to refresh.</>
                )}
              </p>
            </div>
            <Badge variant={data.source === "uploaded" ? "success" : "info"}>
              {data.source === "uploaded" ? "Live (uploaded)" : "Seed"}
            </Badge>
          </div>
          <ul className="space-y-3">
            {data.topEntities.map((row, i) => {
              const org = ALL_ORGANIZATIONS.find((o) => o.slug === row.entitySlug);
              const max = data.topEntities[0]?.netSales ?? 1;
              return (
                <li key={row.entitySlug + i}>
                  <div className="flex items-center justify-between gap-3 text-sm">
                    <Link
                      href={`/app/entities/${row.entitySlug}`}
                      className="font-medium hover:underline inline-flex items-center gap-2"
                    >
                      <span className="text-muted-foreground tabular-nums">{i + 1}.</span>
                      <span>{org?.emoji ?? ""}</span>
                      <span>{org?.name ?? row.toastName}</span>
                    </Link>
                    <span className="font-mono tabular-nums">{formatCurrency(row.netSales)}</span>
                  </div>
                  <Progress value={(row.netSales / max) * 100} className="mt-1.5 h-1" />
                </li>
              );
            })}
          </ul>
          <Button asChild variant="outline" size="sm" className="mt-6 w-full">
            <Link href="/app/toast">View full Toast breakdown →</Link>
          </Button>
        </CardContent>
      </Card>
    </>
  );
}

function MetricCard({
  label,
  value,
  hint,
  placeholder,
  source,
  tone = "neutral",
}: {
  label: string;
  value: string;
  hint?: string;
  placeholder?: boolean;
  source?: "uploaded" | "seed";
  tone?: "neutral" | "brand" | "emerald" | "amber" | "violet" | "rose";
}) {
  const accent: Record<string, string> = {
    neutral: "border-l-border",
    brand: "border-l-[var(--sag-brand)]",
    emerald: "border-l-emerald-500/70",
    amber: "border-l-amber-500/70",
    violet: "border-l-violet-500/70",
    rose: "border-l-rose-500/70",
  };
  return (
    <Card className={`card-interactive border-l-4 ${accent[tone]}`}>
      <CardContent className="p-5">
        <div className="flex items-center justify-between gap-2">
          <div className="section-label">{label}</div>
          {source === "uploaded" && (
            <span className="text-[10px] text-emerald-600 dark:text-emerald-400 font-semibold inline-flex items-center gap-1">
              <span className="inline-block h-1.5 w-1.5 rounded-full bg-emerald-500" /> LIVE
            </span>
          )}
        </div>
        <div
          className={`mt-2 text-2xl md:text-3xl font-semibold stat-value ${
            placeholder ? "text-muted-foreground" : "text-foreground"
          }`}
        >
          {value}
        </div>
        {hint && <div className="mt-1 text-xs text-muted-foreground">{hint}</div>}
      </CardContent>
    </Card>
  );
}
