"use client";

/**
 * Admin → AI Monitor — premium operations-center surface.
 *
 * Three hero stat cards (24h / 7d / 30d) + severity filter chips +
 * action substring search. Feed renders rows with a severity-
 * coloured left border (red = critical, amber = warning,
 * transparent = clean) and an expandable detail panel per row
 * showing the full prompt + response + metadata.
 */

import { useEffect, useMemo, useState } from "react";
import {
  Shield, Search, Loader2, ChevronLeft, ChevronRight, AlertTriangle,
  XCircle, CheckCircle2, ChevronDown, DollarSign,
} from "lucide-react";
import {
  PageHeader, StatCard, Card, CardHeader, EmptyState, Skel,
} from "@/components/admin";

type Severity = "none" | "warning" | "critical" | "blocked";
interface Row {
  id: string;
  userId: string | null;
  brandId: string | null;
  feature: string;
  model: string;
  userPrompt: string;
  aiResponse: string;
  tokensUsed: number | null;
  costEstimate: number | null;
  guardrailFlags: string[];
  flagSeverity: Severity;
  timestamp: string;
}

interface StatsWindow { total: number; warning: number; critical: number; flagRate: number; totalCost: number; totalTokens: number }
interface CostByBrandRow {
  brandId: string;
  brandName: string;
  calls: number;
  totalCost: number;
  totalTokens: number;
  avgCostPerCall: number;
}
interface Feed {
  rows: Row[]; total: number; page: number; limit: number; hasMore: boolean;
  stats: { d1: StatsWindow; d7: StatsWindow; d30: StatsWindow };
  topFeatures: Array<{ feature: string; count: number; totalCost: number; totalTokens: number }>;
  costByBrand: CostByBrandRow[];
  scope: { brandId: string; brandName: string | null };
}
interface BrandOption { id: string; name: string }

const SEVERITY_META: Record<Severity, { label: string; chip: string; icon: typeof Shield; border: string }> = {
  none:     { label: "Clean",    chip: "bg-slate-100 text-slate-600 border-slate-200",      icon: CheckCircle2, border: "border-l-transparent" },
  warning:  { label: "Warning",  chip: "bg-amber-50 text-amber-700 border-amber-200",       icon: AlertTriangle, border: "border-l-amber-500" },
  critical: { label: "Critical", chip: "bg-rose-50 text-rose-700 border-rose-200",          icon: XCircle, border: "border-l-rose-500" },
  blocked:  { label: "Blocked",  chip: "bg-rose-100 text-rose-800 border-rose-300",         icon: XCircle, border: "border-l-rose-700" },
};

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

const SEVERITY_PILLS: Array<{ id: string; label: string }> = [
  { id: "",         label: "All" },
  { id: "critical", label: "Critical" },
  { id: "warning",  label: "Warning" },
  { id: "none",     label: "Clean" },
];

export default function AdminAiMonitorPage() {
  const [severity, setSeverity] = useState<string>("");
  const [feature, setFeature] = useState<string>("");
  const [brandId, setBrandId] = useState<string>("all");
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  const [feed, setFeed] = useState<Feed | null>(null);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [brands, setBrands] = useState<BrandOption[]>([]);

  function toggleExpanded(id: string) {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }

  // Mount-once: brand list for the dropdown — same source as the
  // admin overview page.
  useEffect(() => {
    fetch("/api/admin/brands?limit=200")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (Array.isArray(d?.brands)) {
          setBrands(d.brands.map((b: { id: string; name: string }) => ({ id: b.id, name: b.name })));
        }
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    const handle = setTimeout(() => {
      const params = new URLSearchParams();
      if (severity) params.set("severity", severity);
      if (feature) params.set("feature", feature);
      if (brandId && brandId !== "all") params.set("brandId", brandId);
      if (q.trim()) params.set("q", q.trim());
      params.set("page", String(page));
      setLoading(true);
      fetch(`/api/admin/ai-monitor?${params.toString()}`)
        .then((r) => (r.ok ? r.json() : null))
        .then((d) => setFeed(d))
        .finally(() => setLoading(false));
    }, 250);
    return () => clearTimeout(handle);
  }, [severity, feature, brandId, q, page]);

  const totalPages = useMemo(() => feed ? Math.max(1, Math.ceil(feed.total / feed.limit)) : 1, [feed]);
  const scopeLabel = brandId === "all"
    ? "All Brands"
    : (feed?.scope.brandName ?? brands.find((b) => b.id === brandId)?.name ?? "Selected brand");

  return (
    <div className="space-y-6 transition-opacity duration-200">
      <PageHeader
        title="AI Monitor"
        subtitle={
          feed
            ? `${feed.total.toLocaleString()} matching interactions · ${scopeLabel} · guardrail-scored on the way in`
            : "Loading…"
        }
        icon={Shield}
        actions={
          <select
            value={brandId}
            onChange={(e) => { setBrandId(e.target.value); setPage(1); }}
            className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg min-w-[200px]"
          >
            <option value="all">All Brands</option>
            {brands.map((b) => (<option key={b.id} value={b.id}>{b.name}</option>))}
          </select>
        }
      />

      {/* Hero stats — three windows, scoped to the selected brand */}
      {feed ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <WindowCard label="Last 24h" scope={scopeLabel} stats={feed.stats.d1} />
          <WindowCard label="Last 7d"  scope={scopeLabel} stats={feed.stats.d7} />
          <WindowCard label="Last 30d" scope={scopeLabel} stats={feed.stats.d30} />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="bg-white border border-slate-100 rounded-xl shadow-sm p-4 space-y-2">
              <Skel className="h-3 w-20 bg-slate-100 rounded" />
              <Skel className="h-8 w-32 bg-slate-200 rounded" />
              <Skel className="h-4 w-full bg-slate-100 rounded" />
            </div>
          ))}
        </div>
      )}

      {/* Cost by Brand — only when viewing the unfiltered platform.
          Click a row to switch the dropdown to that brand. */}
      {brandId === "all" && feed && feed.costByBrand.length > 0 && (
        <Card>
          <CardHeader title="Cost by brand · last 30 days" />
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-slate-50/60 text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                <tr>
                  <th className="text-left px-4 py-2">Brand</th>
                  <th className="text-right px-4 py-2">AI calls</th>
                  <th className="text-right px-4 py-2">Tokens</th>
                  <th className="text-right px-4 py-2">Est. cost</th>
                  <th className="text-right px-4 py-2">Avg / call</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {feed.costByBrand.map((b) => (
                  <tr
                    key={b.brandId}
                    onClick={() => { setBrandId(b.brandId); setPage(1); }}
                    className="hover:bg-slate-50 cursor-pointer transition-colors"
                  >
                    <td className="px-4 py-2 font-semibold text-slate-800 truncate max-w-[260px]">{b.brandName}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{b.calls.toLocaleString()}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-600">{b.totalTokens.toLocaleString()}</td>
                    <td className="px-4 py-2 text-right tabular-nums font-semibold text-slate-900">${b.totalCost.toFixed(2)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-500">${b.avgCostPerCall.toFixed(4)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="px-4 py-2 border-t border-slate-100 flex items-center gap-1.5 text-[10px] text-slate-400">
            <DollarSign className="w-3 h-3" />
            Sorted by spend · click a row to drill into that brand.
          </div>
        </Card>
      )}

      {/* Filter bar */}
      <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-3 flex items-center gap-2 flex-wrap">
        {/* Severity pills */}
        <div className="inline-flex bg-slate-100 rounded-lg p-0.5">
          {SEVERITY_PILLS.map((p) => (
            <button
              key={p.id}
              onClick={() => { setSeverity(p.id); setPage(1); }}
              className={`px-3 py-1 text-[11px] font-semibold rounded-md transition-colors ${
                severity === p.id ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"
              }`}
            >
              {p.label}
            </button>
          ))}
        </div>
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" />
          <input
            value={q}
            onChange={(e) => { setQ(e.target.value); setPage(1); }}
            placeholder="Search prompt or response…"
            className="w-full pl-9 pr-3 py-2 text-sm bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"
          />
        </div>
        <select
          value={feature}
          onChange={(e) => { setFeature(e.target.value); setPage(1); }}
          className="px-3 py-2 text-xs bg-white border border-slate-200 rounded-lg min-w-[160px]"
        >
          <option value="">All features</option>
          {(feed?.topFeatures ?? []).map((f) => (
            <option key={f.feature} value={f.feature}>{f.feature} ({f.count})</option>
          ))}
        </select>
      </div>

      {/* Feed */}
      {loading && !feed ? (
        <div className="space-y-2">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="bg-white border border-slate-100 rounded-xl shadow-sm p-4">
              <Skel className="h-3 w-1/3 bg-slate-100 rounded mb-2" />
              <Skel className="h-3 w-2/3 bg-slate-100 rounded" />
            </div>
          ))}
        </div>
      ) : !feed || feed.rows.length === 0 ? (
        <Card>
          <EmptyState
            icon={Shield}
            title="No AI interactions in this filter"
            description="Once Claude / OpenAI calls flow through logAiInteraction(), they'll appear here, guardrail-scored."
          />
        </Card>
      ) : (
        <div className="space-y-2">
          {feed.rows.map((row) => {
            const meta = SEVERITY_META[row.flagSeverity];
            const isOpen = expanded.has(row.id);
            const Icon = meta.icon;
            return (
              <div
                key={row.id}
                className={`bg-white rounded-xl shadow-sm border border-slate-100 border-l-4 ${meta.border} transition-shadow hover:shadow-md`}
              >
                <button
                  type="button"
                  onClick={() => toggleExpanded(row.id)}
                  className="w-full text-left px-4 py-3"
                >
                  <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                    <span className={`inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${meta.chip}`}>
                      <Icon className="w-3 h-3" />
                      {meta.label}
                    </span>
                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500">{row.feature}</span>
                    <span className="text-[10px] text-slate-400 font-mono">{row.model}</span>
                    {row.guardrailFlags.length > 0 && (
                      <div className="flex items-center gap-1">
                        {row.guardrailFlags.slice(0, 3).map((f) => (
                          <span key={f} className="text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded bg-rose-50 text-rose-700 border border-rose-200">
                            {f.replace(/_/g, " ")}
                          </span>
                        ))}
                      </div>
                    )}
                    <span className="text-[10px] text-slate-400 tabular-nums ml-auto flex items-center gap-1.5">
                      {formatTime(row.timestamp)}
                      <ChevronDown className={`w-3 h-3 text-slate-400 transition-transform ${isOpen ? "rotate-180" : ""}`} />
                    </span>
                  </div>
                  <p className="text-xs text-slate-700 line-clamp-1">
                    <span className="font-semibold text-slate-500">Prompt:</span> {row.userPrompt}
                  </p>
                  {!isOpen && (
                    <p className="text-xs text-slate-500 line-clamp-1 mt-0.5">
                      <span className="font-semibold text-slate-500">Response:</span> {row.aiResponse}
                    </p>
                  )}
                </button>
                {isOpen && (
                  <div className="px-4 pb-4 pt-1 space-y-3 border-t border-slate-100">
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">User prompt</p>
                      <pre className="text-[11px] bg-slate-50 border border-slate-200 rounded-lg p-3 whitespace-pre-wrap overflow-auto max-h-48">{row.userPrompt}</pre>
                    </div>
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">AI response</p>
                      <pre className="text-[11px] bg-slate-50 border border-slate-200 rounded-lg p-3 whitespace-pre-wrap overflow-auto max-h-72">{row.aiResponse}</pre>
                    </div>
                    {row.guardrailFlags.length > 0 && (
                      <div>
                        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">All guardrail flags</p>
                        <div className="flex flex-wrap gap-1">
                          {row.guardrailFlags.map((f) => (
                            <span key={f} className="text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded bg-rose-50 text-rose-700 border border-rose-200">
                              {f.replace(/_/g, " ")}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                    <div className="grid grid-cols-3 gap-2 text-[11px]">
                      <span className="text-slate-500">Tokens: <span className="font-semibold text-slate-800 tabular-nums">{row.tokensUsed?.toLocaleString() ?? "—"}</span></span>
                      <span className="text-slate-500">Cost: <span className="font-semibold text-slate-800 tabular-nums">{row.costEstimate != null ? `$${row.costEstimate.toFixed(4)}` : "—"}</span></span>
                      <span className="text-slate-500">When: <span className="font-semibold text-slate-800">{formatTime(row.timestamp)}</span></span>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Pagination */}
      {feed && feed.total > feed.limit && (
        <div className="flex items-center justify-between text-xs text-slate-500">
          <span>Page {page} of {totalPages}</span>
          <div className="flex items-center gap-2">
            <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              <ChevronLeft className="w-3 h-3" /> Prev
            </button>
            <button onClick={() => setPage((p) => p + 1)} disabled={!feed.hasMore} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              Next <ChevronRight className="w-3 h-3" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Window stats card ────────────────────────────────────────────

function WindowCard({ label, scope, stats }: { label: string; scope: string; stats: StatsWindow }) {
  return (
    <Card>
      <div className="p-4">
        <div className="flex items-center justify-between mb-2">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 truncate">
            {label} <span className="text-slate-400">— {scope}</span>
          </p>
          <span className="text-[10px] text-slate-400 shrink-0 ml-2">{stats.totalTokens.toLocaleString()} tokens</span>
        </div>
        <div className="grid grid-cols-3 gap-2">
          <div>
            <p className="text-[10px] text-slate-400 uppercase tracking-wider">Calls</p>
            <p className="text-xl font-semibold text-slate-800 tabular-nums">{stats.total.toLocaleString()}</p>
          </div>
          <div>
            <p className="text-[10px] text-slate-400 uppercase tracking-wider">Flag rate</p>
            <p className={`text-xl font-semibold tabular-nums ${stats.flagRate > 5 ? "text-amber-600" : "text-slate-800"}`}>
              {stats.flagRate}%
            </p>
          </div>
          <div>
            <p className="text-[10px] text-slate-400 uppercase tracking-wider">Critical</p>
            <p className={`text-xl font-semibold tabular-nums ${stats.critical > 0 ? "text-rose-600" : "text-slate-800"}`}>
              {stats.critical.toLocaleString()}
            </p>
          </div>
        </div>
        <p className="mt-3 text-xs text-slate-500">Spend: <span className="font-semibold text-slate-800">${stats.totalCost.toFixed(2)}</span></p>
      </div>
    </Card>
  );
}

void StatCard;
