"use client";

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

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

type AdminOverview = {
  totalProducts: number;
  mappedProducts: number;
  unmappedProducts: number;
  merchantCount: number;
  categoryMappingCount: number;
};

export default function AdminLandingPage() {
  const [overview, setOverview] = useState<AdminOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function load() {
      try {
        setLoading(true);
        setError(null);
        const res = await fetch(`${API_BASE_URL}/api/admin/dashboard/overview`);
        if (!res.ok) {
          throw new Error(`Failed to load dashboard (${res.status})`);
        }
        const data: AdminOverview = await res.json();
        setOverview(data);
      } catch (e: any) {
        console.error(e);
        setError(e.message ?? "Failed to load admin dashboard");
      } finally {
        setLoading(false);
      }
    }

    load();
  }, []);

  return (
    <main className="min-h-screen bg-black text-zinc-50">
      <div className="mx-auto max-w-6xl px-4 py-8">
        <header className="flex items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">
              Battl Builder – Admin
            </h1>
            <p className="mt-1 text-sm text-zinc-400">
              Control room for feeds, mappings, and catalog health.
            </p>
          </div>
        </header>

        {loading && (
          <p className="mt-6 text-sm text-zinc-400">Loading dashboard…</p>
        )}

        {error && (
          <p className="mt-6 text-sm text-red-400">Error: {error}</p>
        )}

        {overview && !loading && !error && (
          <>
            {/* Stats row */}
            <section className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <div className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-4">
                <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">
                  Total Products
                </p>
                <p className="mt-2 text-2xl font-semibold">
                  {overview.totalProducts.toLocaleString()}
                </p>
              </div>

              <div className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-4">
                <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">
                  Mapped Products
                </p>
                <p className="mt-2 text-2xl font-semibold text-emerald-400">
                  {overview.mappedProducts.toLocaleString()}
                </p>
              </div>

              <div className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-4">
                <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">
                  Unmapped Products
                </p>
                <p className="mt-2 text-2xl font-semibold text-amber-400">
                  {overview.unmappedProducts.toLocaleString()}
                </p>
                <p className="mt-1 text-[0.7rem] text-zinc-500">
                  Products still in <code>PENDING_MAPPING</code>.
                </p>
              </div>

              <div className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-4">
                <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">
                  Merchants / Mappings
                </p>
                <p className="mt-2 text-lg font-semibold">
                  {overview.merchantCount}{" "}
                  <span className="text-xs font-normal text-zinc-400">
                    merchants
                  </span>
                </p>
                <p className="text-sm text-zinc-400">
                  {overview.categoryMappingCount.toLocaleString()} mappings
                </p>
              </div>
            </section>

            {/* Nav cards */}
            <section className="mt-10">
              <h2 className="text-xs font-semibold uppercase tracking-[0.18em] text-zinc-500">
                Admin Tools
              </h2>
              <div className="mt-3 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {/* Bulk Mapping */}
                <Link
                  href="/admin/mapping"
                  className="group rounded-lg border border-zinc-800 bg-zinc-950/70 p-4 transition hover:border-amber-400/80 hover:bg-zinc-900/70"
                >
                  <p className="text-sm font-semibold text-zinc-50">
                    Bulk Category Mapping
                  </p>
                  <p className="mt-1 text-xs text-zinc-400">
                    Bucket raw merchant categories and map them to part roles to
                    keep the catalog clean.
                  </p>
                  <p className="mt-3 text-xs text-amber-300">
                    {overview.unmappedProducts.toLocaleString()} products
                    pending mapping
                  </p>
                </Link>

                {/* Import Status */}
                <Link
                  href="/admin/import-status"
                  className="group rounded-lg border border-zinc-800 bg-zinc-950/70 p-4 transition hover:border-amber-400/80 hover:bg-zinc-900/70"
                >
                  <p className="text-sm font-semibold text-zinc-50">
                    Import Status
                  </p>
                  <p className="mt-1 text-xs text-zinc-400">
                    Inspect last feed runs, per-merchant health, and errors.
                  </p>
                  <p className="mt-3 text-xs text-zinc-500 group-hover:text-zinc-300">
                    View import summaries &nbsp;→
                  </p>
                </Link>

                {/* Placeholder for future admin tools */}
                <Link
                  href="/admin/products"
                  className="group rounded-lg border border-zinc-900 bg-zinc-950/40 p-4 transition hover:border-amber-400/80 hover:bg-zinc-900/70"
                >
                  <p className="text-sm font-semibold text-zinc-50">
                    Catalog Explorer
                  </p>
                  <p className="mt-1 text-xs text-zinc-400">
                    (Future) Browse normalized products, offers, and compatibility.
                  </p>
                  <p className="mt-3 text-xs text-zinc-500 group-hover:text-zinc-300">
                    Coming soon
                  </p>
                </Link>
              </div>
            </section>
          </>
        )}
      </div>
    </main>
  );
}