"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

type Stats = {
  quality?: { total: number; avgScore: number };
  duplicates?: { pending: number };
  errors?: { open: number; total: number };
  perf?: { worstP95Ms: number; routeCount: number };
  outdated?: { total: number };
  digest?: { lastRun: string | null };
};

export function OpsCommandCenter() {
  const [stats, setStats] = useState<Stats>({});

  useEffect(() => {
    void Promise.all([
      fetch("/api/admin/quality").then((r) => r.json()).catch(() => null),
      fetch("/api/admin/duplicates").then((r) => r.json()).catch(() => null),
      fetch("/api/admin/errors").then((r) => r.json()).catch(() => null),
      fetch("/api/admin/perf").then((r) => r.json()).catch(() => null),
      fetch("/api/admin/outdated").then((r) => r.json()).catch(() => null),
      fetch("/api/admin/digest").then((r) => r.json()).catch(() => null),
    ]).then(([q, d, e, p, o, dg]) => {
      setStats({
        quality: q ? { total: q.total ?? 0, avgScore: q.avgScore ?? 0 } : undefined,
        duplicates: { pending: d?.stats?.PENDING ?? 0 },
        errors: {
          open: (e?.errors ?? []).filter((x: { resolved: boolean }) => !x.resolved).length,
          total: e?.totalErrors ?? 0,
        },
        perf: {
          routeCount: p?.summary?.length ?? 0,
          worstP95Ms: p?.summary?.[0]?.p95Ms ?? 0,
        },
        outdated: { total: (o?.findings ?? []).length },
        digest: {
          lastRun: dg?.history?.[0]?.runAt ?? null,
        },
      });
    });
  }, []);

  const cards = [
    {
      title: "Quality Score",
      value: stats.quality ? `${stats.quality.avgScore}%` : "—",
      sub: stats.quality ? `${stats.quality.total} profila` : "",
      href: "/admin/ops/quality",
      color: "emerald",
    },
    {
      title: "Duplikati",
      value: stats.duplicates ? `${stats.duplicates.pending}` : "—",
      sub: "Pending review",
      href: "/admin/ops/duplicates",
      color: "amber",
    },
    {
      title: "Greške",
      value: stats.errors ? `${stats.errors.open}` : "—",
      sub: `Ukupno: ${stats.errors?.total ?? 0}`,
      href: "/admin/ops/errors",
      color: "rose",
    },
    {
      title: "Performance",
      value: stats.perf ? `${stats.perf.worstP95Ms}ms` : "—",
      sub: `Najsporiji p95 / ${stats.perf?.routeCount ?? 0} ruta`,
      href: "/admin/ops/performance",
      color: "sky",
    },
    {
      title: "Outdated",
      value: stats.outdated ? `${stats.outdated.total}` : "—",
      sub: "Treba refresh",
      href: "/admin/ops/outdated",
      color: "violet",
    },
    {
      title: "Daily digest",
      value: stats.digest?.lastRun
        ? new Date(stats.digest.lastRun).toLocaleDateString("sr-RS")
        : "—",
      sub: "Poslednji digest",
      href: "/admin/ops/digest",
      color: "stone",
    },
  ];

  return (
    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {cards.map((c) => (
        <Link
          key={c.title}
          href={c.href}
          className="rounded-2xl border border-border bg-white p-5 transition hover:border-primary/40 hover:shadow-md"
        >
          <p className="text-xs font-bold uppercase tracking-[0.16em] text-muted-foreground">
            {c.title}
          </p>
          <p className="mt-2 font-display text-3xl font-bold text-foreground">{c.value}</p>
          <p className="mt-1 text-xs text-muted-foreground">{c.sub}</p>
        </Link>
      ))}
    </div>
  );
}
