'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { apiFetch } from '../../../lib/auth';
import { AVAILABLE_MODELS } from '@/lib/models';

interface ModelResult {
  model: string;
  label: string;
  reply: string;
  loading: boolean;
  error?: string;
}

const MODELS = AVAILABLE_MODELS;

export default function ComparePage() {
  const router = useRouter();
  const [prompt, setPrompt] = useState('');
  const [results, setResults] = useState<ModelResult[]>(
    MODELS.map(m => ({ model: m.id, label: m.label, reply: '', loading: false }))
  );
  const [sending, setSending] = useState(false);
  const [showParams, setShowParams] = useState(false);
  const [temperature, setTemperature] = useState(0.7);
  const [topP, setTopP] = useState(1);
  const [maxTokens, setMaxTokens] = useState(2000);

  async function handleCompare() {
    if (!prompt.trim() || sending) return;

    setSending(true);
    const newResults = results.map(r => ({ ...r, reply: '', loading: true, error: undefined }));
    setResults(newResults);

    await Promise.all(
      MODELS.map(async (model, index) => {
        try {
          const res = await apiFetch('/sandbox/chat', {
            method: 'POST',
            body: JSON.stringify({
              model: model.id,
              messages: [{ role: 'user', content: prompt }],
              temperature,
              top_p: topP,
              max_tokens: maxTokens,
            }),
          });
          const data = await res.json();

          setResults(prev => prev.map((r, i) =>
            i === index ? { ...r, reply: data.reply || '无响应', loading: false } : r
          ));
        } catch (e: any) {
          setResults(prev => prev.map((r, i) =>
            i === index ? { ...r, error: e.message, loading: false } : r
          ));
        }
      })
    );

    setSending(false);
  }

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <button onClick={() => router.back()} className="text-sm text-muted-foreground hover:text-brand-600 mb-2 inline-block">
          &larr; 返回沙箱
        </button>
        <h1 className="text-3xl font-bold text-foreground">对比实验室</h1>
        <p className="mt-2 text-muted-foreground">同题对比不同模型的表现</p>
      </div>

      <div className="bg-card rounded-2xl border border-border p-6 mb-8">
        <textarea
          value={prompt}
          onChange={e => setPrompt(e.target.value)}
          placeholder="输入你想对比的问题或提示词..."
          rows={4}
          className="w-full px-4 py-3 border border-border rounded-xl text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring resize-none mb-4"
        />
        <div className="flex items-center justify-between">
          <button
            onClick={handleCompare}
            disabled={sending || !prompt.trim()}
            className="px-6 py-2.5 bg-brand-600 text-white rounded-xl text-sm font-medium hover:bg-brand-700 disabled:opacity-50"
          >
            {sending ? '对比中...' : '开始对比'}
          </button>
          <button onClick={() => setShowParams(!showParams)}
            className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors ${
              showParams
                ? 'bg-accent text-foreground border-border'
                : 'text-muted-foreground border-border hover:text-foreground hover:bg-accent'
            }`}>
            <svg className={`w-3.5 h-3.5 transition-transform ${showParams ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
            </svg>
            高级参数
          </button>
        </div>
        {showParams && (
          <div className="mt-4 grid grid-cols-1 sm:grid-cols-3 gap-4 p-4 bg-muted/30 rounded-xl border border-border">
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="text-xs font-medium text-foreground">Temperature</label>
                <span className="text-xs text-muted-foreground tabular-nums">{temperature.toFixed(1)}</span>
              </div>
              <input type="range" min="0" max="2" step="0.1" value={temperature}
                onChange={e => setTemperature(parseFloat(e.target.value))}
                className="w-full h-1.5 bg-muted rounded-full appearance-none cursor-pointer accent-brand-600" />
            </div>
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="text-xs font-medium text-foreground">Top P</label>
                <span className="text-xs text-muted-foreground tabular-nums">{topP.toFixed(2)}</span>
              </div>
              <input type="range" min="0" max="1" step="0.05" value={topP}
                onChange={e => setTopP(parseFloat(e.target.value))}
                className="w-full h-1.5 bg-muted rounded-full appearance-none cursor-pointer accent-brand-600" />
            </div>
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="text-xs font-medium text-foreground">Max Tokens</label>
                <span className="text-xs text-muted-foreground tabular-nums">{maxTokens}</span>
              </div>
              <input type="range" min="100" max="8192" step="100" value={maxTokens}
                onChange={e => setMaxTokens(parseInt(e.target.value))}
                className="w-full h-1.5 bg-muted rounded-full appearance-none cursor-pointer accent-brand-600" />
            </div>
          </div>
        )}
      </div>

      {results.some(r => r.reply || r.loading || r.error) && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {results.map((result, index) => (
            <div key={index} className="bg-card rounded-2xl border border-border overflow-hidden">
              <div className="bg-muted/50 px-6 py-3 border-b border-border flex items-center justify-between">
                <span className="font-medium text-foreground">{result.label}</span>
                <span className="text-xs text-muted-foreground">{result.model}</span>
              </div>
              <div className="p-6">
                {result.loading ? (
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" />
                    <div className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                    <div className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                  </div>
                ) : result.error ? (
                  <p className="text-red-500 text-sm">{result.error}</p>
                ) : (
                  <p className="text-foreground leading-relaxed whitespace-pre-wrap">{result.reply}</p>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
