"use client";

import { useEffect, useState } from "react";

interface Summary { totalCalls: number; totalTokens: number; totalCostPaise: number; familiesUsingAI: number; avgMs: number; p95Ms: number; redirects: number }
interface IntentRow { intent: string; count: number; avgMs: number; p95Ms: number; tokens: number; costPaise: number }
interface DayRow { date: string; count: number; costPaise: number }
interface SlowRow { id: string; intent: string; durationMs: number; model: string; createdAt: string; familyId: string | null }
interface Data { days: number; summary: Summary; byIntent: IntentRow[]; byDay: DayRow[]; slowest: SlowRow[]; error?: string }

const EMPTY: Data = { days: 30, summary: { totalCalls: 0, totalTokens: 0, totalCostPaise: 0, familiesUsingAI: 0, avgMs: 0, p95Ms: 0, redirects: 0 }, byIntent: [], byDay: [], slowest: [] };
const rupees = (paise: number) => `₹${(paise / 100).toFixed(2)}`;

export default function AdminAI() {
  const [data, setData] = useState<Data>(EMPTY);
  const [loading, setLoading] = useState(true);
  const [days, setDays] = useState(30);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/admin/ai?days=${days}`, { credentials: "include" })
      .then(r => r.json())
      .then(d => {
        setData({
          days: d?.days || days,
          summary: { ...EMPTY.summary, ...(d?.summary || {}) },
          byIntent: Array.isArray(d?.byIntent) ? d.byIntent : [],
          byDay: Array.isArray(d?.byDay) ? d.byDay : [],
          slowest: Array.isArray(d?.slowest) ? d.slowest : [],
          error: d?.error,
        });
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [days]);

  const { summary, byIntent, byDay, slowest } = data;
  const maxDay = Math.max(...byDay.map(d => d.count), 1);

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-start flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold">AI Observability</h1>
          <p className="text-gray-400">Latency, cost, and intent breakdown over the last {days} days</p>
        </div>
        <select value={days} onChange={e => setDays(Number(e.target.value))} className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-1.5 text-sm">
          <option value={7}>Last 7 days</option>
          <option value={30}>Last 30 days</option>
          <option value={90}>Last 90 days</option>
        </select>
      </div>

      {data.error && <div className="bg-rose-500/10 text-rose-400 text-sm p-3 rounded-lg">Feed error: {data.error}</div>}

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card label="API Calls" value={summary.totalCalls} color="text-blue-400" />
        <Card label="Avg latency" value={`${summary.avgMs}ms`} color={summary.avgMs > 4000 ? "text-rose-400" : "text-emerald-400"} />
        <Card label="p95 latency" value={`${summary.p95Ms}ms`} color={summary.p95Ms > 8000 ? "text-rose-400" : "text-amber-400"} />
        <Card label="Cost" value={rupees(summary.totalCostPaise)} color="text-amber-400" />
        <Card label="Total tokens" value={summary.totalTokens.toLocaleString()} color="text-purple-400" />
        <Card label="Families using AI" value={summary.familiesUsingAI} color="text-emerald-400" />
        <Card label="Medical redirects" value={summary.redirects} color={summary.redirects > 0 ? "text-rose-400" : "text-gray-500"} />
        <Card label="Avg cost / call" value={summary.totalCalls ? rupees(summary.totalCostPaise / summary.totalCalls) : "₹0.00"} color="text-gray-300" />
      </div>

      {loading ? <div className="text-gray-400">Loading…</div> : (
        <>
          <div className="bg-gray-800 p-6 rounded-xl">
            <h3 className="text-lg font-semibold mb-4">Calls per day</h3>
            <div className="h-32 flex items-end gap-1">
              {byDay.length === 0 ? <div className="w-full text-center text-gray-500 text-sm self-center">No AI calls in this window</div> :
                byDay.slice(-30).map((d, i) => (
                  <div key={i} title={`${d.date}: ${d.count} calls · ${rupees(d.costPaise)}`} className="flex-1 group">
                    <div className="w-full bg-blue-500 group-hover:bg-blue-400 rounded-t" style={{ height: `${Math.max((d.count / maxDay) * 100, d.count > 0 ? 4 : 0)}%` }} />
                  </div>
                ))}
            </div>
          </div>

          <div className="bg-gray-800 rounded-xl overflow-hidden">
            <h3 className="text-lg font-semibold p-4 pb-3">By intent</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-700"><tr>
                  <th className="px-4 py-2 text-left text-sm font-medium">Intent</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">Calls</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">Avg ms</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">p95 ms</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">Tokens</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">Cost</th>
                </tr></thead>
                <tbody className="divide-y divide-gray-700">
                  {byIntent.length === 0 ? <tr><td colSpan={6} className="px-4 py-6 text-center text-gray-500">No data</td></tr> :
                    byIntent.map(r => (
                      <tr key={r.intent} className="hover:bg-gray-750">
                        <td className="px-4 py-2 text-sm font-medium">{r.intent}</td>
                        <td className="px-4 py-2 text-sm text-right">{r.count}</td>
                        <td className="px-4 py-2 text-sm text-right text-gray-300">{r.avgMs}</td>
                        <td className={`px-4 py-2 text-sm text-right ${r.p95Ms > 8000 ? "text-rose-400" : "text-gray-300"}`}>{r.p95Ms}</td>
                        <td className="px-4 py-2 text-sm text-right text-gray-400">{r.tokens.toLocaleString()}</td>
                        <td className="px-4 py-2 text-sm text-right text-amber-400">{rupees(r.costPaise)}</td>
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="bg-gray-800 rounded-xl overflow-hidden">
            <h3 className="text-lg font-semibold p-4 pb-3">Slowest calls</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-700"><tr>
                  <th className="px-4 py-2 text-left text-sm font-medium">When</th>
                  <th className="px-4 py-2 text-left text-sm font-medium">Intent</th>
                  <th className="px-4 py-2 text-left text-sm font-medium">Model</th>
                  <th className="px-4 py-2 text-right text-sm font-medium">Duration</th>
                </tr></thead>
                <tbody className="divide-y divide-gray-700">
                  {slowest.length === 0 ? <tr><td colSpan={4} className="px-4 py-6 text-center text-gray-500">No data</td></tr> :
                    slowest.map(r => (
                      <tr key={r.id} className="hover:bg-gray-750">
                        <td className="px-4 py-2 text-sm text-gray-400 whitespace-nowrap">{new Date(r.createdAt).toLocaleString()}</td>
                        <td className="px-4 py-2 text-sm">{r.intent}</td>
                        <td className="px-4 py-2 text-sm text-gray-400">{r.model}</td>
                        <td className={`px-4 py-2 text-sm text-right font-medium ${r.durationMs > 8000 ? "text-rose-400" : "text-amber-400"}`}>{r.durationMs}ms</td>
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function Card({ label, value, color }: { label: string; value: string | number; color: string }) {
  return (
    <div className="bg-gray-800 p-4 rounded-xl">
      <div className={`text-2xl font-bold ${color}`}>{value}</div>
      <div className="text-sm text-gray-300 mt-0.5">{label}</div>
    </div>
  );
}
