'use client';

import React, { useState, useEffect } from 'react';
import { X, Save, RotateCcw, Sparkles, Wand2 } from 'lucide-react';

interface PromptEditorProps {
  initialPrompt: string;
  title?: string;
  type?: 'image' | 'video' | 'general';
  onSave: (prompt: string) => void;
  onClose: () => void;
  onOptimize?: (prompt: string) => Promise<string>;
}

export default function PromptEditor({
  initialPrompt,
  title = '编辑提示词',
  type = 'general',
  onSave,
  onClose,
  onOptimize,
}: PromptEditorProps) {
  const [prompt, setPrompt] = useState(initialPrompt);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);

  useEffect(() => {
    setHasChanges(prompt !== initialPrompt);
  }, [prompt, initialPrompt]);

  const handleSave = () => {
    onSave(prompt);
    onClose();
  };

  const handleReset = () => {
    setPrompt(initialPrompt);
  };

  const handleOptimize = async () => {
    if (!onOptimize) return;
    
    setIsOptimizing(true);
    try {
      const optimized = await onOptimize(prompt);
      setPrompt(optimized);
    } catch (error) {
      console.error('Failed to optimize prompt:', error);
    } finally {
      setIsOptimizing(false);
    }
  };

  const getTypeColor = () => {
    switch (type) {
      case 'image':
        return 'text-blue-600 bg-blue-50';
      case 'video':
        return 'text-purple-600 bg-purple-50';
      default:
        return 'text-gray-600 bg-gray-50';
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <div className="flex items-center gap-3">
            <Sparkles className={`w-5 h-5 ${getTypeColor()}`} />
            <h2 className="text-lg font-semibold text-gray-900">{title}</h2>
            {type !== 'general' && (
              <span className={`text-xs px-2 py-1 rounded ${getTypeColor()}`}>
                {type === 'image' ? '图像' : '视频'}
              </span>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="space-y-4">
            {/* Prompt Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                提示词内容
              </label>
              <textarea
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                className="w-full h-64 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-sans text-sm"
                placeholder="输入提示词..."
              />
              <div className="flex items-center justify-between mt-2">
                <span className="text-xs text-gray-500">
                  {prompt.length} 字符
                </span>
                {hasChanges && (
                  <span className="text-xs text-orange-600">未保存的更改</span>
                )}
              </div>
            </div>

            {/* Tips */}
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <h4 className="text-sm font-medium text-blue-900 mb-2">提示词建议</h4>
              <ul className="text-xs text-blue-700 space-y-1">
                {type === 'image' && (
                  <>
                    <li>• 角色和道具应包含&quot;纯白背景&quot;关键词</li>
                    <li>• 场景应避免人物描述，聚焦环境</li>
                    <li>• 使用具体的视觉描述词，避免抽象概念</li>
                  </>
                )}
                {type === 'video' && (
                  <>
                    <li>• 描述具体的动作和运动</li>
                    <li>• 包含镜头运动和角度变化</li>
                    <li>• 避免重复静态画面信息</li>
                  </>
                )}
                <li>• 保持提示词简洁明了，避免冗余</li>
                <li>• 使用自然语言，不要使用标签格式</li>
              </ul>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200 bg-gray-50">
          <div className="flex items-center gap-2">
            {onOptimize && (
              <button
                onClick={handleOptimize}
                disabled={isOptimizing}
                className="flex items-center gap-2 px-4 py-2 text-sm text-purple-600 hover:text-purple-700 hover:bg-purple-50 rounded transition-colors disabled:opacity-50"
              >
                <Wand2 className="w-4 h-4" />
                {isOptimizing ? '优化中...' : 'AI 优化'}
              </button>
            )}
            
            {hasChanges && (
              <button
                onClick={handleReset}
                className="flex items-center gap-2 px-4 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors"
              >
                <RotateCcw className="w-4 h-4" />
                重置
              </button>
            )}
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors"
            >
              取消
            </button>
            <button
              onClick={handleSave}
              disabled={!hasChanges}
              className="flex items-center gap-2 px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save className="w-4 h-4" />
              保存
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
