'use client';

import Link from 'next/link';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
import type { AiInvocationListItem, AiInvocationListQuery, AiInvocationStats } from '@pac/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAiInvocationsList } from './use-ai-invocations';

const ALL = '__all';

export function AiInvocationsListApp() {
  const { state, query, setQuery, refresh } = useAiInvocationsList({ page: 1, pageSize: 20 });

  return (
    <main className="container mx-auto max-w-6xl space-y-4 p-6">
      <Header onRefresh={refresh} />

      {state.status === 'ready' && state.stats && <StatsBar stats={state.stats} />}

      <FilterBar query={query} onChange={setQuery} />

      {state.status === 'loading' && (
        <Card>
          <CardContent className="py-10 text-center text-sm text-muted-foreground">加载中…</CardContent>
        </Card>
      )}

      {state.status === 'error' && (
        <Card>
          <CardContent className="py-10 text-center space-y-2">
            <div className="text-sm text-rose-600">无法加载 AI 调用历史</div>
            <div className="text-xs text-muted-foreground">code={state.code ?? '?'} · {state.message}</div>
            <Button variant="outline" size="sm" onClick={refresh}>重试</Button>
          </CardContent>
        </Card>
      )}

      {state.status === 'ready' && (
        <>
          <InvocationsTable items={state.data.items} />
          <Pagination
            page={state.data.page}
            pageSize={state.data.pageSize}
            total={state.data.total}
            onPage={(p) => setQuery({ page: p })}
          />
        </>
      )}
    </main>
  );
}

// ─────────────────────────────────────────────
// Header
// ─────────────────────────────────────────────

function Header({ onRefresh }: { onRefresh: () => void }) {
  return (
    <header className="flex items-start justify-between gap-4">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">AI 调用调试</h1>
        <p className="mt-1 text-xs text-muted-foreground">
          看历史调用 · 比较 prompt 版本效果 · 监控成本与失败率
        </p>
      </div>
      <Button variant="outline" size="sm" onClick={onRefresh}>
        <RefreshCw className="h-4 w-4" /> 刷新
      </Button>
    </header>
  );
}

// ─────────────────────────────────────────────
// Stats(24h 概览 + 各 callKey 热点)
// ─────────────────────────────────────────────

function StatsBar({ stats }: { stats: AiInvocationStats }) {
  const cards = [
    { label: '24h 调用数', value: stats.count24h.toLocaleString() },
    { label: '24h 成本', value: `¥${stats.cost24h.toFixed(4)}` },
    {
      label: '24h 失败率',
      value: `${(stats.failureRate24h * 100).toFixed(1)}%`,
      warn: stats.failureRate24h > 0.1,
    },
  ];
  return (
    <div className="space-y-3">
      <div className="grid grid-cols-3 gap-3">
        {cards.map((c) => (
          <Card key={c.label}>
            <CardContent className="p-4">
              <div className="text-xs text-muted-foreground">{c.label}</div>
              <div className={'mt-1 text-xl font-semibold ' + (c.warn ? 'text-amber-600' : '')}>{c.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>
      {stats.byCallKey.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>各 call 24h 分布</CardTitle>
            <CardDescription>用于发现热点 / 异常成本</CardDescription>
          </CardHeader>
          <CardContent className="pb-4">
            <ul className="space-y-1.5 text-xs">
              {stats.byCallKey.map((row) => (
                <li key={row.callKey} className="row-quiet flex items-center justify-between px-3 py-1.5">
                  <code className="font-mono">{row.callKey}</code>
                  <div className="flex items-center gap-4 text-muted-foreground">
                    <span className="nums">{row.count} 次</span>
                    <span className="nums">¥{row.costYuan.toFixed(4)}</span>
                    <span className="nums">
                      {row.avgDurationMs !== null ? `${row.avgDurationMs}ms 平均` : '—'}
                    </span>
                  </div>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// Filter Bar
// ─────────────────────────────────────────────

function FilterBar({
  query,
  onChange,
}: {
  query: Partial<AiInvocationListQuery>;
  onChange: (q: Partial<AiInvocationListQuery>) => void;
}) {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Input
        compact
        placeholder="callKey 精确匹配,如 draft_plan_script"
        value={query.callKey ?? ''}
        onChange={(e) => onChange({ callKey: e.target.value.trim() || undefined })}
        className="w-56 font-mono"
      />
      <Input
        compact
        placeholder="promptVersion 精确匹配"
        value={query.promptVersion ?? ''}
        onChange={(e) => onChange({ promptVersion: e.target.value.trim() || undefined })}
        className="w-72 font-mono"
      />
      <Select
        value={query.status ?? ALL}
        onValueChange={(v) => onChange({ status: v === ALL ? undefined : v })}
      >
        <SelectTrigger className="w-36"><SelectValue placeholder="状态" /></SelectTrigger>
        <SelectContent>
          <SelectItem value={ALL}>全部状态</SelectItem>
          <SelectItem value="succeeded">succeeded</SelectItem>
          <SelectItem value="failed">failed</SelectItem>
          <SelectItem value="cached">cached</SelectItem>
          <SelectItem value="running">running</SelectItem>
        </SelectContent>
      </Select>
      <Select
        value={query.evalMode ?? ALL}
        onValueChange={(v) => onChange({ evalMode: v === ALL ? undefined : v })}
      >
        <SelectTrigger className="w-40"><SelectValue placeholder="evalMode" /></SelectTrigger>
        <SelectContent>
          <SelectItem value={ALL}>全部模式</SelectItem>
          <SelectItem value="production">production</SelectItem>
          <SelectItem value="golden_set">golden_set</SelectItem>
          <SelectItem value="shadow">shadow</SelectItem>
          <SelectItem value="manual">manual</SelectItem>
        </SelectContent>
      </Select>
      <div className="ml-auto text-xs text-muted-foreground">每页 {query.pageSize ?? 20}</div>
    </div>
  );
}

// ─────────────────────────────────────────────
// Table
// ─────────────────────────────────────────────

function InvocationsTable({ items }: { items: AiInvocationListItem[] }) {
  if (items.length === 0) {
    return (
      <Card>
        <CardContent className="py-12 text-center text-sm text-muted-foreground">
          无符合条件的调用
        </CardContent>
      </Card>
    );
  }
  return (
    <Card className="overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b text-left text-xs text-muted-foreground">
              <th className="px-4 py-2 font-medium">callKey · prompt 版本</th>
              <th className="px-4 py-2 font-medium">模型</th>
              <th className="px-4 py-2 font-medium">状态</th>
              <th className="px-4 py-2 font-medium nums">token</th>
              <th className="px-4 py-2 font-medium nums">¥ cost</th>
              <th className="px-4 py-2 font-medium nums">耗时</th>
              <th className="px-4 py-2 font-medium">时间</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody>
            {items.map((r) => (
              <tr key={r.id} className="border-b last:border-b-0 transition-colors hover:bg-muted/30">
                <td className="px-4 py-2.5">
                  <code className="text-xs font-semibold">{r.callKey}</code>
                  <div className="mt-0.5 text-[10.5px] text-muted-foreground font-mono">
                    {r.promptVersion}
                  </div>
                </td>
                <td className="px-4 py-2.5">
                  <Badge variant="outline" className="font-mono text-[10.5px] font-normal">
                    {r.modelProvider}/{r.modelName}
                  </Badge>
                  {r.cacheHit && (
                    <span className="ml-1 text-[10.5px] text-muted-foreground">cache</span>
                  )}
                  {r.evalMode !== 'production' && (
                    <Badge variant="outline" className="ml-1 text-[10.5px] font-normal">{r.evalMode}</Badge>
                  )}
                </td>
                <td className="px-4 py-2.5">
                  <StatusPill status={r.status} />
                  {r.errorMessage && (
                    <div className="mt-0.5 max-w-[20rem] truncate text-[10.5px] text-rose-600">
                      {r.errorMessage}
                    </div>
                  )}
                </td>
                <td className="px-4 py-2.5 nums text-xs text-muted-foreground">
                  {r.totalTokens > 0 ? (
                    <>
                      {r.promptTokens} → {r.completionTokens}
                      {(r.cachedInputTokens > 0 || r.reasoningTokens > 0) && (
                        <div className="text-[10.5px]">
                          {r.cachedInputTokens > 0 && (
                            <span className="text-emerald-600 mr-1">
                              cache {Math.round((r.cachedInputTokens / r.promptTokens) * 100)}%
                            </span>
                          )}
                          {r.reasoningTokens > 0 && (
                            <span className="text-amber-600">
                              think {Math.round((r.reasoningTokens / r.completionTokens) * 100)}%
                            </span>
                          )}
                        </div>
                      )}
                    </>
                  ) : (
                    '—'
                  )}
                </td>
                <td className="px-4 py-2.5 nums text-xs">
                  {r.costYuan > 0 ? `¥${r.costYuan.toFixed(4)}` : '—'}
                </td>
                <td className="px-4 py-2.5 nums text-xs text-muted-foreground">
                  {r.durationMs !== null ? `${r.durationMs}ms` : '—'}
                </td>
                <td className="px-4 py-2.5 text-xs text-muted-foreground nums">
                  {r.startedAt.slice(5, 19).replace('T', ' ')}
                </td>
                <td className="px-4 py-2.5 text-right">
                  <Button asChild size="sm" variant="ghost">
                    <Link href={`/admin/ai-invocations/${r.id}`}>详情 →</Link>
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function StatusPill({ status }: { status: string }) {
  const tones: Record<string, string> = {
    succeeded: 'bg-emerald-100 text-emerald-700',
    failed: 'bg-rose-100 text-rose-700',
    cached: 'bg-slate-100 text-slate-700',
    running: 'bg-sky-100 text-sky-700',
  };
  return (
    <span className={'inline-block rounded px-1.5 py-0.5 text-[10.5px] font-medium ' + (tones[status] ?? 'bg-slate-100 text-slate-700')}>
      {status}
    </span>
  );
}

// ─────────────────────────────────────────────
// Pagination
// ─────────────────────────────────────────────

function Pagination({
  page,
  pageSize,
  total,
  onPage,
}: {
  page: number;
  pageSize: number;
  total: number;
  onPage: (p: number) => void;
}) {
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  if (total === 0) return null;
  return (
    <div className="flex items-center justify-between text-xs text-muted-foreground">
      <div>
        共 <span className="nums font-medium text-foreground">{total}</span> 条 · 第{' '}
        <span className="nums font-medium text-foreground">{page}</span> /{' '}
        <span className="nums">{totalPages}</span> 页
      </div>
      <div className="flex items-center gap-1">
        <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => onPage(page - 1)}>
          <ChevronLeft className="h-4 w-4" /> 上一页
        </Button>
        <Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => onPage(page + 1)}>
          下一页 <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    </div>
  );
}
