"use client";

/**
 * /admin/ai-usage — Platform Cost Center
 *
 * Redesigned Apr-2026 from a single-source AI-calls view into a
 * comprehensive platform cost dashboard. Every operational cost
 * flows through this page: AI, database, auth, SERP, hosting,
 * email, CDN. Backed by /api/admin/cost-center.
 *
 * NOTE: the route filename stays /admin/ai-usage to avoid breaking
 * every bookmark in existence. The sidebar label now reads
 * "Cost Center". Future renames can come with a redirect.
 */

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import {
  DollarSign, Sparkles, Database, ShieldCheck, Search, Server,
  Mail, Tag as TagIcon, AlertTriangle, TrendingUp, ExternalLink,
  Loader2, Gauge,
} from "lucide-react";
import {
  PageHeader, SectionHeader, Card, CardHeader, Sparkline,
  TableSkeleton, EmptyState,
} from "@/components/admin";

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

type Range = "thisMonth" | "lastMonth" | "last3m" | "30d" | "90d";

interface AiByModel {
  model: string; calls: number; inputTokens: number; outputTokens: number;
  cost: number; referenceCost: number; isKnownModel: boolean;
}
interface AiByFeature { feature: string; calls: number; cost: number; inputTokens: number; outputTokens: number }
interface DailyPoint { date: string; cost: number }
interface RowCountRow { table: string; rows: number }
interface CostAlert { service: string; message: string; threshold: number; actual: number }
interface BrandCostRow {
  brandId: string; brandName: string;
  aiCost: number; aiCalls: number; eventCount: number;
  dbCostEstimate: number; totalCost: number;
}
interface ServiceLabels { [key: string]: { label: string; vendor: string; vendorUrl: string } }

interface CostPayload {
  scope: { range: Range; fromISO: string; toISO: string; days: number };
  totalCost: number; previousTotalCost: number; trendPct: number;
  alerts: CostAlert[];
  services: {
    ai: { calls: number; inputTokens: number; outputTokens: number; cost: number; avgCostPerCall: number; byModel: AiByModel[]; byFeature: AiByFeature[]; dailyTrend: DailyPoint[]; totalCalls?: number; totalCost?: number; note?: string };
    database: { sizeMb: number; rowCounts: RowCountRow[]; costEstimate: number; growthRateMbPerDay: number; tier: string };
    auth: { mau: number; authentications: number; costEstimate: number };
    serp: { callsTotal: number; byEndpoint: Record<string, number>; cost: number; balance?: number | null; spent?: number; note?: string };
    hosting: { invocations: number; bandwidthGbEstimate: number; costEstimate: number };
    email: { sent: number; cost: number };
    siteTag: { serves: number; collects: number; bandwidthMb: number };
  };
  byBrand: BrandCostRow[];
  projection: { nextMonthEstimate: number; breakdown: Record<string, number> };
  labels: ServiceLabels;
  generatedAt: string;
}

const RANGES: Array<{ id: Range; label: string }> = [
  { id: "thisMonth", label: "This Month" },
  { id: "lastMonth", label: "Last Month" },
  { id: "last3m",    label: "Last 3 Months" },
  { id: "30d",       label: "30d" },
  { id: "90d",       label: "90d" },
];

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

function usd(n: number): string {
  if (n >= 1000) return `$${(n / 1000).toFixed(1)}k`;
  if (n >= 1)    return `$${n.toFixed(2)}`;
  if (n === 0)   return "$0";
  return `$${n.toFixed(4)}`;
}
function bytesMbToGb(mb: number): string {
  if (mb < 1024) return `${mb.toFixed(0)} MB`;
  return `${(mb / 1024).toFixed(2)} GB`;
}
function formatFeature(f: string): string {
  return f.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
function trendTone(pct: number): { text: string; tone: string; arrow: string } {
  if (pct > 0) return { text: `+${pct}%`, tone: "text-rose-600 bg-rose-50 border-rose-200", arrow: "↑" };
  if (pct < 0) return { text: `${pct}%`, tone: "text-emerald-600 bg-emerald-50 border-emerald-200", arrow: "↓" };
  return { text: "flat", tone: "text-slate-500 bg-slate-50 border-slate-200", arrow: "→" };
}

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

export default function CostCenterPage() {
  const [range, setRange] = useState<Range>("thisMonth");
  const [data, setData] = useState<CostPayload | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(() => {
    setLoading(true);
    fetch(`/api/admin/cost-center?range=${range}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d: CostPayload | null) => setData(d))
      .finally(() => setLoading(false));
  }, [range]);

  useEffect(() => { load(); }, [load]);

  const trend = useMemo(() => data ? trendTone(data.trendPct) : null, [data]);

  return (
    <div className="space-y-6">
      <PageHeader
        title="Cost Center"
        subtitle="Every operational cost across AI, database, auth, SERP data, hosting, email, and CDN"
        icon={DollarSign}
        actions={
          <div className="inline-flex bg-slate-100 rounded-lg p-0.5">
            {RANGES.map((r) => (
              <button
                key={r.id}
                onClick={() => setRange(r.id)}
                className={`px-2.5 py-1 text-[11px] font-semibold rounded-md transition-colors ${
                  range === r.id ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >{r.label}</button>
            ))}
          </div>
        }
      />

      {/* Alerts */}
      {data && data.alerts.length > 0 && (
        <div className="space-y-2">
          {data.alerts.map((a) => (
            <div key={a.service} className="rounded-xl border border-rose-200 bg-rose-50/60 px-4 py-2.5 flex items-center gap-3">
              <AlertTriangle className="w-4 h-4 text-rose-600 shrink-0" />
              <p className="text-xs font-semibold text-rose-800 flex-1">{a.message}</p>
              <span className="text-[10px] font-bold uppercase tracking-widest text-rose-700 bg-white border border-rose-200 px-2 py-0.5 rounded">
                {a.service}
              </span>
            </div>
          ))}
        </div>
      )}

      {/* Hero — total cost */}
      <Card>
        <div className="p-6 grid grid-cols-1 md:grid-cols-3 gap-6 items-center">
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Total platform cost</p>
            {data ? (
              <>
                <p className="text-5xl font-bold text-slate-900 tabular-nums leading-tight">{usd(data.totalCost)}</p>
                <div className="flex items-center gap-2 mt-2">
                  {trend && (
                    <span className={`inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full border ${trend.tone}`}>
                      {trend.arrow} {trend.text} vs prior
                    </span>
                  )}
                  <span className="text-[10px] text-slate-400">
                    prior: {usd(data.previousTotalCost)}
                  </span>
                </div>
              </>
            ) : (
              <div className="h-10 w-32 bg-slate-100 rounded animate-pulse mt-2" />
            )}
          </div>
          <div className="md:col-span-2 grid grid-cols-2 md:grid-cols-3 gap-3">
            <MiniStat
              icon={Sparkles}
              label="AI / LLM"
              value={data ? usd(data.services.ai.cost) : "—"}
              sub={data ? `${data.services.ai.calls.toLocaleString()} calls` : ""}
              accent="text-violet-600"
            />
            <MiniStat
              icon={Database}
              label="Database"
              value={data ? usd(data.services.database.costEstimate) : "—"}
              sub={data ? bytesMbToGb(data.services.database.sizeMb) : ""}
              accent="text-blue-600"
            />
            <MiniStat
              icon={Search}
              label="SERP / Keywords"
              value={data ? usd(data.services.serp.cost) : "—"}
              sub={data ? `${data.services.serp.callsTotal.toLocaleString()} calls` : ""}
              accent="text-amber-600"
            />
            <MiniStat
              icon={Server}
              label="Hosting"
              value={data ? usd(data.services.hosting.costEstimate) : "—"}
              sub={data ? `${data.services.hosting.invocations.toLocaleString()} invokes` : ""}
              accent="text-cyan-600"
            />
            <MiniStat
              icon={ShieldCheck}
              label="Auth / Clerk"
              value={data ? usd(data.services.auth.costEstimate) : "—"}
              sub={data ? `${data.services.auth.mau} MAU` : ""}
              accent="text-emerald-600"
            />
            <MiniStat
              icon={Mail}
              label="Email"
              value={data ? usd(data.services.email.cost) : "—"}
              sub={data ? `${data.services.email.sent.toLocaleString()} sent` : ""}
              accent="text-slate-600"
            />
          </div>
        </div>
      </Card>

      {/* Service breakdown grid */}
      <section>
        <SectionHeader title="Service cost breakdown" />
        {loading && !data ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <Card key={i}><div className="p-5 h-40 bg-slate-50/40 animate-pulse" /></Card>
            ))}
          </div>
        ) : !data ? null : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            <ServiceCard
              id="ai" labels={data.labels} cost={data.services.ai.cost}
              icon={Sparkles} accent="text-violet-600" bg="bg-violet-50"
              primaryStat={{ label: "Calls", value: data.services.ai.calls.toLocaleString() }}
              secondaryStat={{ label: "Avg/call", value: usd(data.services.ai.avgCostPerCall) }}
              note={
                data.services.ai.note
                  ?? `${(data.services.ai.inputTokens / 1_000_000).toFixed(2)}M input + ${(data.services.ai.outputTokens / 1_000_000).toFixed(2)}M output tokens`
              }
              sparkline={data.services.ai.dailyTrend.map((p) => p.cost)}
            />
            <ServiceCard
              id="database" labels={data.labels} cost={data.services.database.costEstimate}
              icon={Database} accent="text-blue-600" bg="bg-blue-50"
              primaryStat={{ label: "Storage", value: bytesMbToGb(data.services.database.sizeMb) }}
              secondaryStat={{ label: "Growth", value: `${data.services.database.growthRateMbPerDay.toFixed(1)} MB/day` }}
              note={`Tier: ${data.services.database.tier} · Estimated from usage — verify against Neon billing dashboard`}
            />
            <ServiceCard
              id="auth" labels={data.labels} cost={data.services.auth.costEstimate}
              icon={ShieldCheck} accent="text-emerald-600" bg="bg-emerald-50"
              primaryStat={{ label: "MAU", value: data.services.auth.mau.toLocaleString() }}
              secondaryStat={{ label: "Auth events", value: data.services.auth.authentications.toLocaleString() }}
              note={data.services.auth.mau <= 10_000 ? "Within Clerk free tier (≤ 10K MAU)" : "Above Clerk free tier"}
            />
            <ServiceCard
              id="serp" labels={data.labels} cost={data.services.serp.cost}
              icon={Search} accent="text-amber-600" bg="bg-amber-50"
              primaryStat={{
                label: "Balance",
                value: typeof data.services.serp.balance === "number"
                  ? usd(data.services.serp.balance)
                  : "—",
              }}
              secondaryStat={{ label: "Spent", value: usd(data.services.serp.spent ?? data.services.serp.cost) }}
              note={data.services.serp.note ?? "Estimated from action counts — verify against DataForSEO billing dashboard"}
            />
            <ServiceCard
              id="hosting" labels={data.labels} cost={data.services.hosting.costEstimate}
              icon={Server} accent="text-cyan-600" bg="bg-cyan-50"
              primaryStat={{ label: "Invocations", value: data.services.hosting.invocations.toLocaleString() }}
              secondaryStat={{ label: "Bandwidth", value: `${data.services.hosting.bandwidthGbEstimate.toFixed(2)} GB` }}
              note="Vercel Pro baseline + estimated usage"
            />
            <ServiceCard
              id="email" labels={data.labels} cost={data.services.email.cost}
              icon={Mail} accent="text-slate-600" bg="bg-slate-100"
              primaryStat={{ label: "Sent", value: data.services.email.sent.toLocaleString() }}
              secondaryStat={{ label: "Status", value: data.services.email.sent === 0 ? "Not configured" : "Active" }}
              note="Resend pricing — free tier 3K sends/month"
            />
            <ServiceCard
              id="siteTag" labels={data.labels} cost={0}
              icon={TagIcon} accent="text-indigo-600" bg="bg-indigo-50"
              primaryStat={{ label: "Events collected", value: data.services.siteTag.collects.toLocaleString() }}
              secondaryStat={{ label: "Bandwidth", value: `${data.services.siteTag.bandwidthMb.toFixed(1)} MB` }}
              note="Included in Vercel hosting cost — shown separately for visibility"
            />
          </div>
        )}
      </section>

      {/* AI deep-dive — by feature + by model */}
      {data && data.services.ai.calls > 0 && (
        <section>
          <SectionHeader title="AI usage deep-dive" />
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
            <Card>
              <CardHeader title="By feature" />
              <table className="w-full text-xs">
                <thead className="text-[10px] font-bold uppercase tracking-widest text-slate-400 border-b border-slate-100">
                  <tr>
                    <th className="text-left px-4 py-2">Feature</th>
                    <th className="text-right px-4 py-2">Calls</th>
                    <th className="text-right px-4 py-2">Tokens (in/out)</th>
                    <th className="text-right px-4 py-2">Cost</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {data.services.ai.byFeature.map((f) => (
                    <tr key={f.feature}>
                      <td className="px-4 py-2 font-medium text-slate-800 capitalize">{formatFeature(f.feature)}</td>
                      <td className="px-4 py-2 text-right tabular-nums text-slate-700">{f.calls.toLocaleString()}</td>
                      <td className="px-4 py-2 text-right tabular-nums text-slate-500 text-[10px]">
                        {(f.inputTokens / 1000).toFixed(1)}k / {(f.outputTokens / 1000).toFixed(1)}k
                      </td>
                      <td className="px-4 py-2 text-right tabular-nums font-semibold text-amber-700">{usd(f.cost)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
            <Card>
              <CardHeader title="By model" />
              <table className="w-full text-xs">
                <thead className="text-[10px] font-bold uppercase tracking-widest text-slate-400 border-b border-slate-100">
                  <tr>
                    <th className="text-left px-4 py-2">Model</th>
                    <th className="text-right px-4 py-2">Calls</th>
                    <th className="text-right px-4 py-2">Reference cost</th>
                    <th className="text-right px-4 py-2">Stored cost</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {data.services.ai.byModel.map((m) => (
                    <tr key={m.model}>
                      <td className="px-4 py-2 font-mono text-[10px] text-slate-700 truncate max-w-[260px]" title={m.model}>
                        {m.model}
                        {!m.isKnownModel && (
                          <span className="ml-1 text-[9px] font-semibold text-amber-600">·unpriced</span>
                        )}
                      </td>
                      <td className="px-4 py-2 text-right tabular-nums text-slate-700">{m.calls.toLocaleString()}</td>
                      <td className="px-4 py-2 text-right tabular-nums text-slate-500">{usd(m.referenceCost)}</td>
                      <td className="px-4 py-2 text-right tabular-nums font-semibold text-amber-700">{usd(m.cost)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div className="px-4 py-2 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
                <strong>Reference cost</strong> uses the current pricing table in <code className="font-mono">src/lib/cost-config.ts</code>.
                Divergence from stored cost signals a pricing-table update is needed.
              </div>
            </Card>
          </div>
        </section>
      )}

      {/* Cost by brand */}
      {data && data.byBrand.length > 0 && (
        <section>
          <SectionHeader title="Cost by brand"
            right={<span className="text-[10px] text-slate-400">Top {data.byBrand.length} by AI spend</span>}
          />
          <Card>
            <table className="w-full text-xs">
              <thead className="text-[10px] font-bold uppercase tracking-widest text-slate-400 border-b border-slate-100 bg-slate-50/40">
                <tr>
                  <th className="text-left px-4 py-2">Brand</th>
                  <th className="text-right px-4 py-2">AI cost</th>
                  <th className="text-right px-4 py-2">AI calls</th>
                  <th className="text-right px-4 py-2">Events</th>
                  <th className="text-right px-4 py-2">DB estimate</th>
                  <th className="text-right px-4 py-2">Total</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {data.byBrand.map((b) => (
                  <tr key={b.brandId} className="hover:bg-slate-50">
                    <td className="px-4 py-2 font-medium text-slate-800 truncate max-w-[260px]">{b.brandName}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-amber-700 font-semibold">{usd(b.aiCost)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-600">{b.aiCalls.toLocaleString()}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-600">{b.eventCount.toLocaleString()}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-500">{usd(b.dbCostEstimate)}</td>
                    <td className="px-4 py-2 text-right tabular-nums font-bold text-slate-900">{usd(b.totalCost)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="px-4 py-2.5 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
              Helps identify brands whose cost-to-serve exceeds their plan price. Auth + hosting + SERP costs are platform-shared
              and not prorated here.
            </div>
          </Card>
        </section>
      )}

      {/* Next-month projection */}
      {data && (
        <section>
          <SectionHeader title="Next-month projection"
            right={<span className="text-[10px] text-slate-400">Linear run-rate — not a forecast</span>}
          />
          <Card>
            <div className="p-5 grid grid-cols-1 md:grid-cols-5 gap-4">
              <div className="md:col-span-2">
                <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Estimated next month</p>
                <p className="text-4xl font-bold text-slate-900 tabular-nums leading-tight mt-1">
                  {usd(data.projection.nextMonthEstimate)}
                </p>
                <p className="text-[11px] text-slate-500 mt-1 leading-relaxed">
                  AI extrapolated from current daily rate; fixed services repeat. Not a forecast —
                  a budget check for end-of-month sizing.
                </p>
              </div>
              <div className="md:col-span-3 grid grid-cols-2 md:grid-cols-3 gap-2">
                {Object.entries(data.projection.breakdown).map(([service, cost]) => (
                  <div key={service} className="bg-slate-50 rounded-lg p-3 border border-slate-100">
                    <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">{data.labels[service]?.label ?? service}</p>
                    <p className="text-base font-bold text-slate-900 tabular-nums">{usd(cost)}</p>
                  </div>
                ))}
              </div>
            </div>
          </Card>
        </section>
      )}

      {/* Empty state — when no data at all */}
      {!loading && data && data.services.ai.calls === 0 && data.services.siteTag.collects === 0 && (
        <Card>
          <EmptyState
            icon={Gauge}
            title="No cost data in this window"
            description="Try widening the range, or pick Last Month to see prior-month costs."
          />
        </Card>
      )}

      {loading && !data && (
        <div className="space-y-3">
          <TableSkeleton rows={3} />
          <TableSkeleton rows={5} />
        </div>
      )}
    </div>
  );
}

// ─── Helper components ────────────────────────────────────────────

function MiniStat({
  icon: Icon, label, value, sub, accent,
}: {
  icon: typeof Sparkles;
  label: string;
  value: string;
  sub: string;
  accent: string;
}) {
  return (
    <div className="bg-slate-50/60 rounded-lg p-3 border border-slate-100">
      <div className="flex items-center justify-between mb-1">
        <p className="text-[9px] font-bold uppercase tracking-widest text-slate-500">{label}</p>
        <Icon className={`w-3.5 h-3.5 ${accent}`} />
      </div>
      <p className="text-lg font-bold text-slate-900 tabular-nums leading-tight">{value}</p>
      {sub && <p className="text-[10px] text-slate-400 mt-0.5">{sub}</p>}
    </div>
  );
}

function ServiceCard({
  id, labels, cost, icon: Icon, accent, bg,
  primaryStat, secondaryStat, note, sparkline,
}: {
  id: string;
  labels: ServiceLabels;
  cost: number;
  icon: typeof Sparkles;
  accent: string;
  bg: string;
  primaryStat: { label: string; value: string };
  secondaryStat: { label: string; value: string };
  note: string;
  sparkline?: number[];
}) {
  const meta = labels[id];
  return (
    <Card>
      <div className="p-5 flex flex-col h-full">
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-2">
            <span className={`w-8 h-8 rounded-lg ${bg} ${accent} flex items-center justify-center`}>
              <Icon className="w-4 h-4" />
            </span>
            <div>
              <p className="text-xs font-bold text-slate-800">{meta?.label ?? id}</p>
              <p className="text-[10px] text-slate-400">{meta?.vendor ?? "—"}</p>
            </div>
          </div>
          <span className="text-lg font-bold text-slate-900 tabular-nums">{usd(cost)}</span>
        </div>
        <div className="grid grid-cols-2 gap-3 mb-3">
          <div>
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-500">{primaryStat.label}</p>
            <p className="text-sm font-semibold text-slate-900 tabular-nums">{primaryStat.value}</p>
          </div>
          <div>
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-500">{secondaryStat.label}</p>
            <p className="text-sm font-semibold text-slate-900 tabular-nums">{secondaryStat.value}</p>
          </div>
        </div>
        {sparkline && sparkline.length > 0 && (
          <div className="h-8 mb-3">
            <Sparkline points={sparkline} color="#8B5CF6" />
          </div>
        )}
        <p className="text-[10px] text-slate-500 leading-relaxed flex-1">{note}</p>
        {meta?.vendorUrl && (
          <Link
            href={meta.vendorUrl}
            target="_blank"
            rel="noopener"
            className="inline-flex items-center gap-1 text-[10px] font-semibold text-slate-600 hover:text-slate-900 mt-2"
          >
            Open {meta.vendor} dashboard <ExternalLink className="w-2.5 h-2.5" />
          </Link>
        )}
      </div>
    </Card>
  );
}

// TrendingUp is imported for potential future use (sparkline trend arrows);
// reference it here so the tree-shaker doesn't strip the import.
void TrendingUp;
