'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { apiFetch, getToken } from '@/lib/auth';
import { AVAILABLE_MODELS, DEFAULT_MODEL } from '@/lib/models';
import { ModelSelector } from '@/components/ui/model-selector';
import { API_BASE } from '@/lib/config';

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

export default function PromptWorkshopPage() {
  const router = useRouter();
  const { isLoggedIn } = useAuth();
  const [prompt, setPrompt] = useState('');
  const [variables, setVariables] = useState<Record<string, string>>({});
  const [messages, setMessages] = useState<Message[]>([
    { role: 'assistant', content: '欢迎使用提示词工坊！输入你的提示词，测试不同模型的效果。' },
  ]);
  const [sending, setSending] = useState(false);
  const [model, setModel] = useState(DEFAULT_MODEL);
  const [showSave, setShowSave] = useState(false);
  const [saveTitle, setSaveTitle] = useState('');
  const [saveDesc, setSaveDesc] = useState('');
  const [saveTags, setSaveTags] = useState('');
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

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

    const userMsg: Message = { role: 'user', content: prompt };
    setMessages(prev => [...prev, userMsg]);
    setSending(true);

    try {
      const tk = getToken();
      let reply = '';
      if (tk) {
        const res = await fetch(`${API_BASE}/sandbox/chat`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${tk}`,
          },
          body: JSON.stringify({
            model,
            messages: [...messages, userMsg].map(m => ({ role: m.role, content: m.content })),
          }),
        });
        const data = await res.json();
        reply = data.reply || '无响应';
      } else {
        await new Promise(r => setTimeout(r, 600));
        reply = `你输入的提示词是：\n\n${prompt}\n\n---\n登录后可测试真实模型回复。`;
      }
      setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
    } catch (e: any) {
      setMessages(prev => [...prev, { role: 'assistant', content: `错误: ${e.message}` }]);
    } finally {
      setSending(false);
    }
  }

  function insertVariable(name: string) {
    setPrompt(prev => prev + `{{${name}}}`);
  }

  async function handleSave() {
    if (!saveTitle.trim() || saving) return;
    setSaving(true);
    try {
      await apiFetch('/prompts', {
        method: 'POST',
        body: JSON.stringify({
          title: saveTitle,
          content: prompt,
          description: saveDesc || undefined,
          tags: saveTags || undefined,
          model: model === 'general' ? undefined : model,
        }),
      });
      setSaved(true);
      setShowSave(false);
      setSaveTitle('');
      setSaveDesc('');
      setSaveTags('');
      setTimeout(() => setSaved(false), 3000);
    } catch (e: any) {
      alert('保存失败: ' + e.message);
    } finally {
      setSaving(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>
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">提示词工坊</h1>
            <p className="mt-2 text-muted-foreground">编写、测试、优化你的提示词</p>
          </div>
          {saved && (
            <span className="text-sm text-green-600 font-medium">保存成功！</span>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="space-y-4">
          <div className="bg-card rounded-2xl border border-border p-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">
              <h3 className="font-semibold text-foreground">提示词编辑</h3>
              <ModelSelector value={model} onChange={setModel} className="w-full sm:w-48" />
            </div>

            <textarea
              value={prompt}
              onChange={e => setPrompt(e.target.value)}
              placeholder={'输入你的提示词...\n使用 {{变量名}} 定义变量\n\n例如：你是一名{{角色}}，请帮我{{任务}}'}
              rows={12}
              className="w-full px-4 py-3 border border-border rounded-xl text-sm font-mono bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring resize-none"
            />

            <div className="mt-4 flex flex-wrap gap-2">
              <button
                onClick={handleTest}
                disabled={sending || !prompt.trim()}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700 disabled:opacity-50"
              >
                {sending ? '测试中...' : '测试提示词'}
              </button>
              <button
                onClick={() => {
                  setPrompt('');
                  setMessages([{ role: 'assistant', content: '欢迎使用提示词工坊！' }]);
                }}
                className="px-4 py-2 border border-border rounded-lg text-sm text-foreground hover:bg-accent"
              >
                清空
              </button>
              {isLoggedIn && prompt.trim() && (
                <button
                  onClick={() => setShowSave(true)}
                  className="px-4 py-2 border border-border rounded-lg text-sm text-brand-600 hover:bg-accent"
                >
                  保存到提示词库
                </button>
              )}
            </div>
          </div>

          <div className="bg-card rounded-2xl border border-border p-6">
            <h3 className="font-semibold text-foreground mb-4">变量设置</h3>
            <div className="space-y-3">
              {['角色', '任务', '输出格式', '约束条件'].map(varName => (
                <div key={varName} className="flex items-center gap-3">
                  <span className="text-sm text-muted-foreground w-20">{varName}:</span>
                  <input
                    type="text"
                    value={variables[varName] || ''}
                    onChange={e => setVariables(prev => ({ ...prev, [varName]: e.target.value }))}
                    placeholder={`输入${varName}...`}
                    className="flex-1 px-3 py-1.5 border border-border rounded-lg text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                  />
                  <button
                    onClick={() => insertVariable(varName)}
                    className="text-xs text-brand-600 hover:underline"
                  >
                    插入
                  </button>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="bg-card rounded-2xl border border-border p-6">
          <h3 className="font-semibold text-foreground mb-4">测试结果</h3>
          <div className="h-[60vh] overflow-y-auto space-y-4">
            {messages.map((msg, i) => (
              <div key={i} className={`flex gap-3 ${msg.role === 'user' ? 'justify-end' : ''}`}>
                {msg.role === 'assistant' && (
                  <div className="w-8 h-8 bg-brand-600 rounded-xl flex items-center justify-center text-white text-xs font-bold shrink-0">
                    Y
                  </div>
                )}
                <div className={`max-w-[80%] rounded-2xl px-4 py-2.5 text-sm ${
                  msg.role === 'user'
                    ? 'bg-brand-600 text-white'
                    : 'bg-muted text-foreground'
                }`}>
                  {msg.content}
                </div>
                {msg.role === 'user' && (
                  <div className="w-8 h-8 bg-muted-foreground/20 rounded-xl flex items-center justify-center text-xs font-bold shrink-0">
                    我
                  </div>
                )}
              </div>
            ))}
            {sending && (
              <div className="flex gap-3">
                <div className="w-8 h-8 bg-brand-600 rounded-xl flex items-center justify-center text-white text-xs font-bold">
                  Y
                </div>
                <div className="bg-muted rounded-2xl rounded-tl-none px-4 py-2.5">
                  <span className="inline-flex gap-1">
                    <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" />
                    <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                    <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                  </span>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {showSave && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => setShowSave(false)}>
          <div className="bg-card rounded-2xl border border-border p-6 w-full max-w-lg mx-4 shadow-xl" onClick={e => e.stopPropagation()}>
            <h3 className="text-lg font-semibold text-foreground mb-4">保存提示词</h3>
            <div className="space-y-3">
              <div>
                <label className="text-sm font-medium text-foreground block mb-1">标题 *</label>
                <input type="text" value={saveTitle} onChange={e => setSaveTitle(e.target.value)}
                  placeholder="提示词标题"
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring" />
              </div>
              <div>
                <label className="text-sm font-medium text-foreground block mb-1">描述</label>
                <input type="text" value={saveDesc} onChange={e => setSaveDesc(e.target.value)}
                  placeholder="简短描述这个提示词的用途"
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring" />
              </div>
              <div>
                <label className="text-sm font-medium text-foreground block mb-1">标签</label>
                <input type="text" value={saveTags} onChange={e => setSaveTags(e.target.value)}
                  placeholder="用逗号分隔，如：编程,Python,调试"
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring" />
              </div>
            </div>
            <div className="flex justify-end gap-2 mt-6">
              <button onClick={() => setShowSave(false)}
                className="px-4 py-2 border border-border rounded-lg text-sm text-foreground hover:bg-accent">
                取消
              </button>
              <button onClick={handleSave} disabled={saving || !saveTitle.trim()}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700 disabled:opacity-50">
                {saving ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
