"use client";

/**
 * Admin → All Audits & Reports
 * ────────────────────────────
 * Three tabs: Technical Audits / Performance Audits / Content
 * Briefs. Each tab lists the 100 most-recent rows across the
 * platform with the parent brand for context.
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import { FileSearch, Loader2, Gauge, FileText, AlertTriangle, RefreshCw } from "lucide-react";

interface Brand { id: string; name: string; domain: string }
interface TechRow { id: string; crawlHealth: number; status: string; pagesScanned: number; createdAt: string; brand: Brand }
interface PerfRow { id: string; status: string; device: string; score: number | null; createdAt: string; brand: Brand }
interface BriefRow { id: string; title: string; type: string; primaryKeyword: string | null; status: string; createdAt: string; brand: Brand }

interface Payload {
  counts: { technicalAudits: number; performanceAudits: number; contentBriefs: number };
  technicalAudits: TechRow[];
  performanceAudits: PerfRow[];
  contentBriefs: BriefRow[];
}

type Tab = "technical" | "performance" | "briefs";

function formatDate(s: string): string {
  try { return new Date(s).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }); } catch { return s; }
}

export default function AdminContentPage() {
  const [data, setData] = useState<Payload | null>(null);
  const [tab, setTab] = useState<Tab>("technical");
  const [error, setError] = useState<string | null>(null);
  const [retryKey, setRetryKey] = useState(0);

  useEffect(() => {
    // 10-second cap + structured error state so an API 500 / timeout
    // renders a "Failed to load" card with Retry instead of leaving
    // the page stuck on a spinner (previously: `if (!data) return
    // <spinner>` with no error path).
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10_000);
    setError(null);
    fetch("/api/admin/content", { signal: controller.signal })
      .then(async (r) => {
        if (!r.ok) {
          let msg = `HTTP ${r.status}`;
          try {
            const body = await r.json();
            if (body?.error) msg = `${msg}: ${body.error}`;
          } catch {}
          throw new Error(msg);
        }
        return r.json() as Promise<Payload>;
      })
      .then((d) => setData(d))
      .catch((err: Error) => {
        if (err.name === "AbortError") {
          setError("Request timed out after 10s. Retry to try again.");
        } else {
          setError(err.message || "Failed to load audits.");
        }
      })
      .finally(() => clearTimeout(timeoutId));
    return () => {
      clearTimeout(timeoutId);
      controller.abort();
    };
  }, [retryKey]);

  if (error) {
    return (
      <div className="max-w-2xl mx-auto mt-16">
        <div className="rounded-xl border border-rose-200 bg-rose-50 p-6 text-center">
          <AlertTriangle className="w-8 h-8 text-rose-500 mx-auto mb-2" />
          <h2 className="text-sm font-bold text-slate-900">Couldn&apos;t load Audits &amp; Reports</h2>
          <p className="text-xs text-slate-600 mt-1">{error}</p>
          <button
            onClick={() => setRetryKey((k) => k + 1)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 mt-4 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50"
          >
            <RefreshCw className="w-3 h-3" /> Retry
          </button>
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="w-5 h-5 text-slate-400 animate-spin" />
      </div>
    );
  }

  const TABS: Array<{ id: Tab; label: string; count: number; icon: typeof FileSearch }> = [
    { id: "technical",   label: "Technical Audits",   count: data.counts.technicalAudits,   icon: FileSearch },
    { id: "performance", label: "Performance Audits", count: data.counts.performanceAudits, icon: Gauge },
    { id: "briefs",      label: "Content Briefs",     count: data.counts.contentBriefs,     icon: FileText },
  ];

  return (
    <div className="space-y-5">
      <div>
        <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
          <FileSearch className="w-5 h-5 text-slate-700" /> All Audits &amp; Reports
        </h1>
        <p className="text-slate-500 text-sm mt-1">
          Most-recent content surfaces across every brand. Drill into a brand from the link in any row.
        </p>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 border-b border-slate-200 overflow-x-auto">
        {TABS.map((t) => {
          const Icon = t.icon;
          const active = tab === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-semibold whitespace-nowrap border-b-2 transition-colors ${
                active
                  ? "border-slate-900 text-slate-900"
                  : "border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300"
              }`}
            >
              <Icon className="w-3.5 h-3.5" />
              {t.label}
              <span className="text-[10px] font-bold text-slate-400 bg-slate-100 rounded-full px-1.5 py-0.5 tabular-nums">
                {t.count.toLocaleString()}
              </span>
            </button>
          );
        })}
      </div>

      {tab === "technical" && <TechTable rows={data.technicalAudits} />}
      {tab === "performance" && <PerfTable rows={data.performanceAudits} />}
      {tab === "briefs" && <BriefsTable rows={data.contentBriefs} />}
    </div>
  );
}

function TechTable({ rows }: { rows: TechRow[] }) {
  if (rows.length === 0) return <Empty msg="No technical audits yet." />;
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 border-b border-slate-200">
          <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
            <th className="text-left px-4 py-3">Brand</th>
            <th className="text-left px-3 py-3">Status</th>
            <th className="text-right px-3 py-3">Score</th>
            <th className="text-right px-3 py-3">Pages</th>
            <th className="text-right px-3 py-3">When</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100">
          {rows.map((r) => (
            <tr key={r.id} className="hover:bg-slate-50">
              <td className="px-4 py-2.5">
                <Link href={`/admin/brands?q=${encodeURIComponent(r.brand.domain)}`} className="text-xs font-semibold text-slate-800 hover:text-brand-600 truncate block max-w-[260px]">
                  {r.brand.name}
                </Link>
                <p className="text-[10px] text-slate-500 font-mono truncate max-w-[260px]">{r.brand.domain}</p>
              </td>
              <td className="px-3 py-2.5"><StatusChip status={r.status} /></td>
              <td className={`px-3 py-2.5 text-right text-xs font-bold tabular-nums ${
                r.crawlHealth >= 80 ? "text-emerald-600" : r.crawlHealth >= 50 ? "text-amber-600" : "text-red-600"
              }`}>{r.crawlHealth}/100</td>
              <td className="px-3 py-2.5 text-right text-xs text-slate-700 tabular-nums">{r.pagesScanned}</td>
              <td className="px-3 py-2.5 text-right text-[10px] text-slate-500 tabular-nums">{formatDate(r.createdAt)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PerfTable({ rows }: { rows: PerfRow[] }) {
  if (rows.length === 0) return <Empty msg="No performance audits yet." />;
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 border-b border-slate-200">
          <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
            <th className="text-left px-4 py-3">Brand</th>
            <th className="text-left px-3 py-3">Device</th>
            <th className="text-left px-3 py-3">Status</th>
            <th className="text-right px-3 py-3">When</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100">
          {rows.map((r) => (
            <tr key={r.id} className="hover:bg-slate-50">
              <td className="px-4 py-2.5">
                <Link href={`/admin/brands?q=${encodeURIComponent(r.brand.domain)}`} className="text-xs font-semibold text-slate-800 hover:text-brand-600 truncate block max-w-[260px]">
                  {r.brand.name}
                </Link>
                <p className="text-[10px] text-slate-500 font-mono truncate max-w-[260px]">{r.brand.domain}</p>
              </td>
              <td className="px-3 py-2.5">
                <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500">{r.device}</span>
              </td>
              <td className="px-3 py-2.5"><StatusChip status={r.status} /></td>
              <td className="px-3 py-2.5 text-right text-[10px] text-slate-500 tabular-nums">{formatDate(r.createdAt)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function BriefsTable({ rows }: { rows: BriefRow[] }) {
  if (rows.length === 0) return <Empty msg="No content briefs yet." />;
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 border-b border-slate-200">
          <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
            <th className="text-left px-4 py-3">Brand</th>
            <th className="text-left px-3 py-3">Title</th>
            <th className="text-left px-3 py-3">Keyword</th>
            <th className="text-left px-3 py-3">Type</th>
            <th className="text-left px-3 py-3">Status</th>
            <th className="text-right px-3 py-3">When</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100">
          {rows.map((r) => (
            <tr key={r.id} className="hover:bg-slate-50">
              <td className="px-4 py-2.5">
                <Link href={`/admin/brands?q=${encodeURIComponent(r.brand.domain)}`} className="text-xs font-semibold text-slate-800 hover:text-brand-600 truncate block max-w-[200px]">
                  {r.brand.name}
                </Link>
              </td>
              <td className="px-3 py-2.5 text-xs text-slate-700 truncate max-w-[260px]">{r.title}</td>
              <td className="px-3 py-2.5 text-xs text-slate-500 truncate max-w-[180px]">{r.primaryKeyword ?? "—"}</td>
              <td className="px-3 py-2.5">
                <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500">{r.type}</span>
              </td>
              <td className="px-3 py-2.5"><StatusChip status={r.status} /></td>
              <td className="px-3 py-2.5 text-right text-[10px] text-slate-500 tabular-nums">{formatDate(r.createdAt)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function StatusChip({ status }: { status: string }) {
  const cls =
    status === "completed" ? "bg-emerald-50 text-emerald-700 border-emerald-200"
    : status === "running" ? "bg-blue-50 text-blue-700 border-blue-200"
    : status === "failed" ? "bg-red-50 text-red-700 border-red-200"
    : status === "draft" ? "bg-slate-100 text-slate-600 border-slate-200"
    : "bg-amber-50 text-amber-700 border-amber-200";
  return <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${cls}`}>{status}</span>;
}

function Empty({ msg }: { msg: string }) {
  return <div className="bg-white border border-slate-200 rounded-xl p-12 text-center text-slate-400 text-sm">{msg}</div>;
}
