"use client";

import { useState, useCallback } from "react";
import {
  Wrench, Loader2, Play, CheckCircle2, AlertTriangle, Database,
  Activity, Shield, Bot, Bug, ChevronDown, ChevronUp, RefreshCw,
  Server, Zap, Users, Clock, Trash2, Plus, XCircle, Heart,
} from "lucide-react";

// ─── Types ──────────────────────────────────────────────────────────────────────

interface BackfillResult {
  brandsProcessed: number; totalSessionsScanned: number;
  aiReferralsFound: number; googleAiOverviewFound: number;
  otherAiPlatformFound: number; attributionsCreated: number;
  queryContextPatched?: number;
  byBrand: Record<string, { scanned: number; found: number; created: number; googleAiOverview: number; otherPlatforms: number }>;
}

interface MetricRow {
  brandId: string; name: string; domain: string;
  totalSnapshots: number; dateRange: string;
  totalConversions: number; totalSessions: number;
  status: "healthy" | "suspicious" | "corrupted";
}

interface CronRow {
  route: string; schedule: string; lastRun: string | null;
  lastStatus: string; lastDuration: number | null; lastDetails: string | null;
}

interface TableRow { name: string; rows: number }
interface SiteRow { brandId: string; name: string; domain: string; lastEventAt: string | null; status: string; hoursSinceLastEvent: number }
interface BrandRow { id: string; name: string; domain: string; organization: string; plan: string; status: string; createdAt: string; lastActivity: string | null }
interface ErrorRow { id: string; route: string; method: string; status: number; message: string; brandId: string | null; createdAt: string }
interface FreshnessSource { lastDate?: string | null; lastUpdatedAt?: string | null; lastEventAt?: string | null; status: "fresh" | "stale" | "critical" | "none" }
interface FreshnessRow { brandId: string; name: string; domain: string; ga4: FreshnessSource; gsc: FreshnessSource; siteTag: FreshnessSource; dataforseo: FreshnessSource }

interface BrandHealthRow {
  brandId: string; brandName: string; domain: string; healthStatus: string;
  openAlert: {
    id: string; status: string; firstDetectedAt: string; expectedRate: number;
    actualRate: number; dropPct: number; consecutiveHoursDegraded: number; lastCheckedAt: string;
  } | null;
}
interface BrandHealthStatus { summary: { total: number; healthy: number; degraded: number; down: number }; brands: BrandHealthRow[] }

// ─── Helpers ────────────────────────────────────────────────────────────────────

function api(action: string, method: "GET" | "POST" = "GET", body?: Record<string, unknown>) {
  if (method === "GET") return fetch(`/api/admin/tools?action=${action}`).then((r) => r.json());
  return fetch("/api/admin/tools", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action, ...body }) }).then((r) => r.json());
}

function useAction<T>(fetcher: () => Promise<T>) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const run = useCallback(async () => {
    setLoading(true); setError(null);
    try { setData(await fetcher()); } catch (e) { setError(e instanceof Error ? e.message : "Failed"); }
    setLoading(false);
  }, [fetcher]);
  return { data, loading, error, run };
}

function StatusDot({ status }: { status: string }) {
  const color = status === "healthy" || status === "active" || status === "success" ? "bg-emerald-500"
    : status === "suspicious" || status === "slow" || status === "warning" ? "bg-amber-400"
    : status === "never" ? "bg-slate-300"
    : "bg-red-500";
  return <span className={`inline-block w-2 h-2 rounded-full ${color}`} />;
}

function Nfmt({ n }: { n: number | null | undefined }) {
  return <>{(n ?? 0).toLocaleString()}</>;
}

function Section({ title, icon: Icon, children, defaultOpen = false }: {
  title: string; icon: typeof Database; children: React.ReactNode; defaultOpen?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border border-slate-200 rounded-xl overflow-hidden">
      <button onClick={() => setOpen(!open)} className="w-full flex items-center gap-2 px-5 py-3.5 bg-slate-50 hover:bg-slate-100 transition-colors text-left">
        <Icon className="w-4 h-4 text-brand-600" />
        <span className="text-sm font-bold text-slate-800 flex-1">{title}</span>
        {open ? <ChevronUp className="w-4 h-4 text-slate-400" /> : <ChevronDown className="w-4 h-4 text-slate-400" />}
      </button>
      {open && <div className="p-5 space-y-4 bg-white">{children}</div>}
    </div>
  );
}

function Card({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
  return (
    <div className="bg-white rounded-lg border border-slate-200 p-4 space-y-3">
      <div>
        <h3 className="text-sm font-bold text-slate-800">{title}</h3>
        {description && <p className="text-xs text-slate-500 mt-0.5">{description}</p>}
      </div>
      {children}
    </div>
  );
}

function ActionBtn({ onClick, loading, icon: Icon, children, color = "brand" }: {
  onClick: () => void; loading: boolean; icon: typeof Play; children: React.ReactNode; color?: "brand" | "red" | "emerald";
}) {
  const cls = color === "red" ? "bg-red-600 hover:bg-red-700" : color === "emerald" ? "bg-emerald-600 hover:bg-emerald-700" : "bg-brand-600 hover:bg-brand-700";
  return (
    <button onClick={onClick} disabled={loading} className={`inline-flex items-center gap-1.5 px-3 py-1.5 ${cls} text-white text-xs font-semibold rounded-lg disabled:opacity-50`}>
      {loading ? <Loader2 className="w-3 h-3 animate-spin" /> : <Icon className="w-3 h-3" />}
      {children}
    </button>
  );
}

function ErrorBanner({ error }: { error: string | null }) {
  if (!error) return null;
  return (
    <div className="flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg">
      <AlertTriangle className="w-4 h-4 text-red-600 shrink-0 mt-0.5" />
      <p className="text-xs text-red-700">{error}</p>
    </div>
  );
}

function SuccessBanner({ message }: { message: string }) {
  return (
    <div className="flex items-start gap-2 p-3 bg-emerald-50 border border-emerald-200 rounded-lg">
      <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0 mt-0.5" />
      <p className="text-xs text-emerald-700 font-semibold">{message}</p>
    </div>
  );
}

const th = "px-3 py-2 text-[10px] font-bold uppercase tracking-widest text-slate-400";
const td = "px-3 py-2 text-xs";

// ─── Page ─────────────────────────────────────────────────────────────────────────

export default function AdminToolsPage() {
  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 py-8 space-y-4">
      <div className="flex items-center gap-2 mb-2">
        <Wrench className="w-5 h-5 text-slate-400" />
        <h1 className="text-xl font-bold text-slate-900">Admin Tools</h1>
      </div>

      <Section title="Data Management" icon={Database} defaultOpen>
        <MetricAuditCard />
        <Ga4PurgeCard />
        <BackfillCard />
        <FillQueriesCard />
      </Section>

      <Section title="System Health" icon={Server}>
        <BrandHealthMonitorCard />
        <SourceFreshnessCard />
        <CronStatusCard />
        <TableSizesCard />
        <SiteTagHealthCard />
      </Section>

      <Section title="User & Brand Management" icon={Users}>
        <BrandStatusCard />
      </Section>

      <Section title="AI Attribution Tools" icon={Bot}>
        <TestReferralCard />
      </Section>

      <Section title="Debugging" icon={Bug}>
        <ErrorLogCard />
      </Section>
    </div>
  );
}

// ─── Data Management Cards ───────────────────────────────────────────────────────────

function MetricAuditCard() {
  const { data, loading, error, run } = useAction<{ brands: MetricRow[] }>(
    useCallback(() => api("metric-audit"), []),
  );
  return (
    <Card title="MetricSnapshot Audit" description="Auto-scan all brands for GA4 data anomalies.">
      <ActionBtn onClick={run} loading={loading} icon={Activity}>Scan All Brands</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Brand</th>
              <th className={`${th} text-right`}>Snapshots</th>
              <th className={`${th} text-right`}>Conversions</th>
              <th className={`${th} text-right`}>Sessions</th>
              <th className={`${th} text-center`}>Status</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.brands.map((b) => (
                <tr key={b.brandId}>
                  <td className={`${td} font-semibold text-slate-800`}>{b.name}<br/><span className="text-[10px] text-slate-400">{b.dateRange}</span></td>
                  <td className={`${td} text-right tabular-nums`}><Nfmt n={b.totalSnapshots} /></td>
                  <td className={`${td} text-right tabular-nums`}><Nfmt n={b.totalConversions} /></td>
                  <td className={`${td} text-right tabular-nums`}><Nfmt n={b.totalSessions} /></td>
                  <td className={`${td} text-center`}><StatusDot status={b.status} /> <span className="ml-1">{b.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

function Ga4PurgeCard() {
  const [brandId, setBrandId] = useState("");
  const { data, loading, error, run } = useAction<{ purged: number }>(
    useCallback(() => api("ga4-purge", "POST", { brandId }), [brandId]),
  );
  return (
    <Card title="GA4 Data Purge" description="Remove corrupted MetricSnapshot rows where conversions > sessions × 5.">
      <div className="flex items-center gap-2">
        <input value={brandId} onChange={(e) => setBrandId(e.target.value)} placeholder="Brand ID (cuid)" className="flex-1 text-xs border border-slate-200 rounded-lg px-3 py-1.5" />
        <ActionBtn onClick={run} loading={loading} icon={Trash2} color="red">Purge</ActionBtn>
      </div>
      <ErrorBanner error={error} />
      {data && <SuccessBanner message={`Purged ${data.purged} corrupted rows`} />}
    </Card>
  );
}

function BackfillCard() {
  const [result, setResult] = useState<BackfillResult | null>(null);
  const [running, setRunning] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const run = async () => {
    setRunning(true); setError(null); setResult(null);
    try {
      const res = await fetch("/api/admin/backfill-ai-referrals", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) });
      if (!res.ok) { setError(`HTTP ${res.status}`); return; }
      setResult(await res.json());
    } catch (e) { setError(e instanceof Error ? e.message : "Failed"); }
    setRunning(false);
  };

  return (
    <Card title="AI Referral Backfill" description="Scan TrackedSession records for AI platform referrers and Google AI Overview clicks.">
      <ActionBtn onClick={run} loading={running} icon={Play}>Run Backfill</ActionBtn>
      <ErrorBanner error={error} />
      {result && (
        <div className="space-y-2">
          <SuccessBanner message={`Found ${result.aiReferralsFound} AI referrals, created ${result.attributionsCreated} attributions${result.queryContextPatched ? `, patched ${result.queryContextPatched} queries` : ""}`} />
          {Object.keys(result.byBrand).length > 0 && (
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead><tr className="border-b border-slate-100">
                  <th className={`${th} text-left`}>Brand</th>
                  <th className={`${th} text-right`}>Scanned</th>
                  <th className={`${th} text-right`}>Found</th>
                  <th className={`${th} text-right`}>Google AIO</th>
                  <th className={`${th} text-right`}>Other AI</th>
                  <th className={`${th} text-right`}>Created</th>
                </tr></thead>
                <tbody className="divide-y divide-slate-50">
                  {Object.entries(result.byBrand).map(([name, s]) => (
                    <tr key={name}>
                      <td className={`${td} font-semibold text-slate-800`}>{name}</td>
                      <td className={`${td} text-right tabular-nums`}><Nfmt n={s.scanned} /></td>
                      <td className={`${td} text-right tabular-nums`}>{s.found}</td>
                      <td className={`${td} text-right tabular-nums text-blue-600 font-semibold`}>{s.googleAiOverview}</td>
                      <td className={`${td} text-right tabular-nums text-violet-600 font-semibold`}>{s.otherPlatforms}</td>
                      <td className={`${td} text-right tabular-nums text-emerald-600 font-semibold`}>{s.created}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </Card>
  );
}

function FillQueriesCard() {
  const { data, loading, error, run } = useAction<{ nullBefore: number; patched: number }>(
    useCallback(() => api("fill-queries", "POST"), []),
  );
  return (
    <Card title="Query Inference Runner" description="Infer query context from landing page URL for AiAttribution records with null queryContext.">
      <ActionBtn onClick={run} loading={loading} icon={Zap}>Fill Missing Queries</ActionBtn>
      <ErrorBanner error={error} />
      {data && <SuccessBanner message={`${data.patched} records updated (${data.nullBefore} were null)`} />}
    </Card>
  );
}

// ─── System Health Cards ───────────────────────────────────────────────────────────────────

function CronStatusCard() {
  const { data, loading, error, run } = useAction<{ crons: CronRow[] }>(
    useCallback(() => api("cron-status"), []),
  );
  const [triggering, setTriggering] = useState<string | null>(null);

  const trigger = async (route: string) => {
    setTriggering(route);
    await api("trigger-cron", "POST", { route }).catch(() => null);
    setTriggering(null);
    run();
  };

  return (
    <Card title="Cron Status Dashboard" description="All configured crons with last-run status. Add logCron() wrapper to crons for tracking.">
      <ActionBtn onClick={run} loading={loading} icon={RefreshCw}>Load Status</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Route</th>
              <th className={`${th} text-left`}>Schedule</th>
              <th className={`${th} text-left`}>Last Run</th>
              <th className={`${th} text-center`}>Status</th>
              <th className={`${th} text-right`}>Duration</th>
              <th className={`${th} text-right`}>Action</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.crons.map((c) => (
                <tr key={c.route}>
                  <td className={`${td} font-mono text-slate-700`}>{c.route.replace("/api/cron/", "")}</td>
                  <td className={`${td} text-slate-500`}>{c.schedule}</td>
                  <td className={`${td} text-slate-500`}>{c.lastRun ? new Date(c.lastRun).toLocaleString() : "—"}</td>
                  <td className={`${td} text-center`}><StatusDot status={c.lastStatus} /> <span className="ml-1">{c.lastStatus}</span></td>
                  <td className={`${td} text-right tabular-nums text-slate-500`}>{c.lastDuration != null ? `${(c.lastDuration / 1000).toFixed(1)}s` : "—"}</td>
                  <td className={`${td} text-right`}>
                    <button
                      onClick={() => trigger(c.route)}
                      disabled={triggering === c.route}
                      className="text-[10px] font-semibold text-brand-600 hover:text-brand-700 disabled:opacity-40"
                    >
                      {triggering === c.route ? "Running…" : "Trigger"}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

function TableSizesCard() {
  const { data, loading, error, run } = useAction<{ tables: TableRow[] }>(
    useCallback(() => api("table-sizes"), []),
  );
  return (
    <Card title="Database Table Sizes" description="Row counts from pg_stat_user_tables, sorted by size.">
      <ActionBtn onClick={run} loading={loading} icon={Database}>Load Sizes</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Table</th>
              <th className={`${th} text-right`}>Rows</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.tables.map((t) => (
                <tr key={t.name} className={t.rows >= 10_000_000 ? "bg-red-50" : t.rows >= 1_000_000 ? "bg-amber-50" : ""}>
                  <td className={`${td} font-mono text-slate-700`}>{t.name}</td>
                  <td className={`${td} text-right tabular-nums font-semibold ${t.rows >= 10_000_000 ? "text-red-600" : t.rows >= 1_000_000 ? "text-amber-600" : "text-slate-800"}`}>
                    <Nfmt n={t.rows} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

function SiteTagHealthCard() {
  const { data, loading, error, run } = useAction<{ sites: SiteRow[] }>(
    useCallback(() => api("site-tag-health"), []),
  );
  return (
    <Card title="Site Tag Health" description="Per-brand Site Tag activity status.">
      <ActionBtn onClick={run} loading={loading} icon={Activity}>Check Health</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Brand</th>
              <th className={`${th} text-left`}>Last Event</th>
              <th className={`${th} text-center`}>Status</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.sites.map((s) => (
                <tr key={s.brandId}>
                  <td className={`${td} font-semibold text-slate-800`}>{s.name}<br/><span className="text-[10px] text-slate-400">{s.domain}</span></td>
                  <td className={`${td} text-slate-500`}>{s.lastEventAt ? `${s.hoursSinceLastEvent}h ago` : "Never"}</td>
                  <td className={`${td} text-center`}><StatusDot status={s.status} /> <span className="ml-1 capitalize">{s.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

// ─── User & Brand Management Cards ───────────────────────────────────────────────────────

function BrandStatusCard() {
  const { data, loading, error, run } = useAction<{ brands: BrandRow[] }>(
    useCallback(() => api("brand-status"), []),
  );
  return (
    <Card title="Brand Status Manager" description="All brands across all organizations.">
      <ActionBtn onClick={run} loading={loading} icon={Users}>Load Brands</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Brand</th>
              <th className={`${th} text-left`}>Organization</th>
              <th className={`${th} text-center`}>Plan</th>
              <th className={`${th} text-center`}>Status</th>
              <th className={`${th} text-left`}>Last Activity</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.brands.map((b) => (
                <tr key={b.id}>
                  <td className={`${td} font-semibold text-slate-800`}>{b.name}<br/><span className="text-[10px] text-slate-400">{b.domain}</span></td>
                  <td className={`${td} text-slate-600`}>{b.organization}</td>
                  <td className={`${td} text-center`}><span className="text-[10px] font-bold uppercase px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">{b.plan}</span></td>
                  <td className={`${td} text-center`}><StatusDot status={b.status === "active" ? "healthy" : "corrupted"} /> <span className="ml-1">{b.status}</span></td>
                  <td className={`${td} text-slate-500`}>{b.lastActivity ? new Date(b.lastActivity).toLocaleDateString() : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

// ─── AI Attribution Tools Cards ──────────────────────────────────────────────────────────

function TestReferralCard() {
  const [brandId, setBrandId] = useState("");
  const [platform, setPlatform] = useState("chatgpt");
  const [landingPage, setLandingPage] = useState("/");
  const [queryContext, setQueryContext] = useState("");
  const { data, loading, error, run } = useAction<{ ok: boolean; id: string }>(
    useCallback(() => api("test-ai-referral", "POST", { brandId, platform, landingPage, queryContext: queryContext || undefined }), [brandId, platform, landingPage, queryContext]),
  );
  return (
    <Card title="Test AI Referral" description="Create a test AiAttribution record for demos and UI verification.">
      <div className="grid grid-cols-2 gap-2">
        <input value={brandId} onChange={(e) => setBrandId(e.target.value)} placeholder="Brand ID" className="text-xs border border-slate-200 rounded-lg px-3 py-1.5" />
        <select value={platform} onChange={(e) => setPlatform(e.target.value)} className="text-xs border border-slate-200 rounded-lg px-3 py-1.5 bg-white">
          <option value="chatgpt">ChatGPT</option>
          <option value="perplexity">Perplexity</option>
          <option value="gemini">Gemini</option>
          <option value="claude">Claude</option>
          <option value="copilot">Copilot</option>
          <option value="google_ai_overview">Google AI Overview</option>
          <option value="meta_ai">Meta AI</option>
        </select>
        <input value={landingPage} onChange={(e) => setLandingPage(e.target.value)} placeholder="Landing page (/about)" className="text-xs border border-slate-200 rounded-lg px-3 py-1.5" />
        <input value={queryContext} onChange={(e) => setQueryContext(e.target.value)} placeholder="Query context (optional)" className="text-xs border border-slate-200 rounded-lg px-3 py-1.5" />
      </div>
      <ActionBtn onClick={run} loading={loading} icon={Plus}>Create Test Referral</ActionBtn>
      <ErrorBanner error={error} />
      {data?.ok && <SuccessBanner message={`Created test attribution: ${data.id}`} />}
    </Card>
  );
}

// ─── Debugging Cards ─────────────────────────────────────────────────────────────────────

function ErrorLogCard() {
  const { data, loading, error, run } = useAction<{ errors: ErrorRow[] }>(
    useCallback(() => api("error-log"), []),
  );
  const [clearing, setClearing] = useState(false);
  const clearOld = async () => {
    setClearing(true);
    await api("clear-errors", "POST").catch(() => null);
    setClearing(false);
    run();
  };

  return (
    <Card title="Error Log Viewer" description="Recent server-side errors captured from API routes.">
      <div className="flex items-center gap-2">
        <ActionBtn onClick={run} loading={loading} icon={Bug}>Load Errors</ActionBtn>
        <ActionBtn onClick={clearOld} loading={clearing} icon={Trash2} color="red">Clear 7d+</ActionBtn>
      </div>
      <ErrorBanner error={error} />
      {data && data.errors.length === 0 && <SuccessBanner message="No errors logged" />}
      {data && data.errors.length > 0 && (
        <div className="overflow-x-auto max-h-80 overflow-y-auto">
          <table className="w-full text-xs">
            <thead className="sticky top-0 bg-white"><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Route</th>
              <th className={`${th} text-center`}>Status</th>
              <th className={`${th} text-left`}>Message</th>
              <th className={`${th} text-left`}>Time</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.errors.map((e) => (
                <tr key={e.id}>
                  <td className={`${td} font-mono text-slate-700`}>{e.route}</td>
                  <td className={`${td} text-center`}><span className={`font-bold ${e.status >= 500 ? "text-red-600" : "text-amber-600"}`}>{e.status}</span></td>
                  <td className={`${td} text-slate-600 max-w-[300px] truncate`} title={e.message}>{e.message}</td>
                  <td className={`${td} text-slate-400`}>{new Date(e.createdAt).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

function SourceFreshnessCard() {
  const { data, loading, error, run } = useAction<{ brands: FreshnessRow[] }>(
    useCallback(() => api("source-freshness"), []),
  );
  const statusColor = (s: string) =>
    s === "fresh" ? "bg-emerald-500" : s === "stale" ? "bg-amber-400" : s === "critical" ? "bg-red-500" : "bg-slate-300";
  const formatTs = (iso: string | null | undefined) => {
    if (!iso) return "—";
    const d = new Date(iso);
    return d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
  };
  return (
    <Card title="Source Freshness by Brand" description="Per-brand data source sync status. Green = fresh, Yellow = stale (12-48h), Red = critical (48h+).">
      <ActionBtn onClick={run} loading={loading} icon={RefreshCw} color="emerald">Check All Brands</ActionBtn>
      <ErrorBanner error={error} />
      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead><tr className="border-b border-slate-100">
              <th className={`${th} text-left`}>Brand</th>
              <th className={`${th} text-center`}>Site Tag</th>
              <th className={`${th} text-center`}>GA4</th>
              <th className={`${th} text-center`}>GSC</th>
              <th className={`${th} text-center`}>DataForSEO</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-50">
              {data.brands.map((b) => (
                <tr key={b.brandId}>
                  <td className={`${td} font-semibold text-slate-800`}>
                    {b.name}
                    <br/><span className="text-[10px] text-slate-400">{b.domain}</span>
                  </td>
                  <td className={`${td} text-center`}>
                    <span className={`inline-block w-2 h-2 rounded-full ${statusColor(b.siteTag.status)}`} />
                    <span className="ml-1 text-slate-500">{formatTs(b.siteTag.lastEventAt)}</span>
                  </td>
                  <td className={`${td} text-center`}>
                    <span className={`inline-block w-2 h-2 rounded-full ${statusColor(b.ga4.status)}`} />
                    <span className="ml-1 text-slate-500">{formatTs(b.ga4.lastUpdatedAt)}</span>
                  </td>
                  <td className={`${td} text-center`}>
                    <span className={`inline-block w-2 h-2 rounded-full ${statusColor(b.gsc.status)}`} />
                    <span className="ml-1 text-slate-500">{formatTs(b.gsc.lastUpdatedAt)}</span>
                  </td>
                  <td className={`${td} text-center`}>
                    <span className={`inline-block w-2 h-2 rounded-full ${statusColor(b.dataforseo.status)}`} />
                    <span className="ml-1 text-slate-500">{formatTs(b.dataforseo.lastUpdatedAt)}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

// ─── Brand Health Monitor Card ───────────────────────────────────────────────────────────

function BrandHealthMonitorCard() {
  const { data, loading, error, run } = useAction<BrandHealthStatus>(
    useCallback(() => fetch("/api/admin/brand-health/status").then((r) => r.json()), []),
  );

  const [checking, setChecking] = useState(false);
  const [checkResult, setCheckResult] = useState<string | null>(null);

  const runCheckNow = useCallback(async () => {
    setChecking(true);
    setCheckResult(null);
    try {
      const res = await fetch("/api/admin/brand-health/check-now").then((r) => r.json()) as { summary: { opened: number; escalatedToDown: number; resolved: number } };
      setCheckResult(`Done — opened: ${res.summary.opened}, escalated: ${res.summary.escalatedToDown}, resolved: ${res.summary.resolved}`);
      await run();
    } catch {
      setCheckResult("Check failed — see console");
    }
    setChecking(false);
  }, [run]);

  const statusColor = (s: string) =>
    s === "healthy" ? "text-emerald-700 bg-emerald-50 border-emerald-200"
    : s === "degraded" ? "text-amber-700 bg-amber-50 border-amber-200"
    : "text-red-700 bg-red-50 border-red-200";

  const fmtPct = (p: number) => `${Math.round(p * 100)}%`;
  const fmtNum = (n: number) => Math.round(n).toLocaleString();
  const fmtAgo = (iso: string) => {
    const h = Math.floor((Date.now() - new Date(iso).getTime()) / 3_600_000);
    return h < 1 ? "<1h ago" : `${h}h ago`;
  };

  return (
    <Card title="Brand Health Monitor" description="Hourly event-rate check per brand. Alerts fire after 2 consecutive hours ≥90% below baseline.">
      <div className="flex items-center gap-2 flex-wrap">
        <ActionBtn onClick={run} loading={loading} icon={RefreshCw}>Load Status</ActionBtn>
        <ActionBtn onClick={runCheckNow} loading={checking} icon={Heart} color="emerald">Run Check Now</ActionBtn>
      </div>
      <ErrorBanner error={error} />
      {checkResult && <SuccessBanner message={checkResult} />}
      {data && (
        <>
          <div className="flex gap-3 text-xs text-slate-600">
            <span className="font-semibold">{data.summary.total} brands</span>
            <span className="text-emerald-700">{data.summary.healthy} healthy</span>
            {data.summary.degraded > 0 && <span className="text-amber-700 font-bold">{data.summary.degraded} degraded</span>}
            {data.summary.down > 0 && <span className="text-red-700 font-bold">{data.summary.down} DOWN</span>}
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead><tr className="border-b border-slate-100">
                <th className={`${th} text-left`}>Brand</th>
                <th className={`${th} text-center`}>Status</th>
                <th className={`${th} text-right`}>Expected/hr</th>
                <th className={`${th} text-right`}>Actual/hr</th>
                <th className={`${th} text-right`}>Drop</th>
                <th className={`${th} text-right`}>Hrs</th>
                <th className={`${th} text-right`}>Since</th>
              </tr></thead>
              <tbody className="divide-y divide-slate-50">
                {data.brands.map((b) => (
                  <tr key={b.brandId}>
                    <td className={`${td} font-semibold text-slate-800`}>
                      {b.brandName}<br/>
                      <span className="text-[10px] text-slate-400">{b.domain}</span>
                    </td>
                    <td className={`${td} text-center`}>
                      <span className={`inline-flex items-center px-1.5 py-0.5 rounded border text-[10px] font-bold uppercase ${statusColor(b.healthStatus)}`}>
                        {b.healthStatus}
                      </span>
                    </td>
                    <td className={`${td} text-right text-slate-500`}>{b.openAlert ? fmtNum(b.openAlert.expectedRate) : "—"}</td>
                    <td className={`${td} text-right text-slate-500`}>{b.openAlert ? fmtNum(b.openAlert.actualRate) : "—"}</td>
                    <td className={`${td} text-right font-bold ${b.healthStatus === "down" ? "text-red-600" : b.healthStatus === "degraded" ? "text-amber-600" : "text-slate-400"}`}>
                      {b.openAlert ? fmtPct(b.openAlert.dropPct) : "—"}
                    </td>
                    <td className={`${td} text-right text-slate-500`}>{b.openAlert ? b.openAlert.consecutiveHoursDegraded : "—"}</td>
                    <td className={`${td} text-right text-slate-400`}>{b.openAlert ? fmtAgo(b.openAlert.firstDetectedAt) : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </Card>
  );
}
