'use client';

import React, { useState } from 'react';
import { Asset, Storyboard } from '@/types';
import { Sparkles, Image as ImageIcon, Video, Edit2, Copy, Check } from 'lucide-react';
import PromptEditor from '@/components/common/PromptEditor';

interface PromptPreviewPanelProps {
  item: Asset | Storyboard;
  onUpdate?: (updates: Partial<Asset | Storyboard>) => void;
  onOptimize?: (prompt: string, type: 'image' | 'video') => Promise<string>;
}

export default function PromptPreviewPanel({
  item,
  onUpdate,
  onOptimize,
}: PromptPreviewPanelProps) {
  const [editingPrompt, setEditingPrompt] = useState<{
    type: 'image' | 'video';
    prompt: string;
  } | null>(null);
  const [copiedPrompt, setCopiedPrompt] = useState<string | null>(null);

  const isStoryboard = 'episodeId' in item;
  const isAsset = 'type' in item && !isStoryboard;

  const imagePrompt = isAsset 
    ? (item as Asset).imagePrompt 
    : (item as Storyboard).mergeImagePrompt;
  
  const videoPrompt = isStoryboard 
    ? (item as Storyboard).videoPrompt 
    : undefined;

  const originalText = isStoryboard 
    ? (item as Storyboard).originalText 
    : undefined;

  const handleCopy = async (prompt: string, type: string) => {
    try {
      await navigator.clipboard.writeText(prompt);
      setCopiedPrompt(type);
      setTimeout(() => setCopiedPrompt(null), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  const handleSavePrompt = (newPrompt: string) => {
    if (!onUpdate || !editingPrompt) return;

    if (editingPrompt.type === 'image') {
      if (isAsset) {
        onUpdate({ imagePrompt: newPrompt } as Partial<Asset>);
      } else {
        onUpdate({ mergeImagePrompt: newPrompt } as Partial<Storyboard>);
      }
    } else {
      onUpdate({ videoPrompt: newPrompt } as Partial<Storyboard>);
    }
  };

  const handleOptimizePrompt = async (prompt: string) => {
    if (!onOptimize || !editingPrompt) return prompt;
    return await onOptimize(prompt, editingPrompt.type);
  };

  if (!imagePrompt && !videoPrompt && !originalText) {
    return (
      <div className="p-8 text-center">
        <Sparkles className="w-12 h-12 text-gray-300 mx-auto mb-3" />
        <p className="text-sm text-gray-500">暂无提示词信息</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Original Text */}
      {originalText && (
        <div className="border border-gray-200 rounded-lg overflow-hidden">
          <div className="px-4 py-3 bg-gray-50 border-b border-gray-200">
            <h3 className="text-sm font-medium text-gray-700">原文</h3>
          </div>
          <div className="p-4 bg-white">
            <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-wrap">
              {originalText}
            </p>
          </div>
        </div>
      )}

      {/* Image Prompt */}
      {imagePrompt && (
        <div className="border border-blue-200 rounded-lg overflow-hidden">
          <div className="px-4 py-3 bg-blue-50 border-b border-blue-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <ImageIcon className="w-4 h-4 text-blue-600" />
                <h3 className="text-sm font-medium text-blue-900">
                  {isAsset ? '生图提示词' : '融图提示词'}
                </h3>
                <span className="text-xs px-2 py-0.5 bg-blue-100 text-blue-700 rounded">
                  白底图
                </span>
              </div>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => handleCopy(imagePrompt, 'image')}
                  className="p-1.5 text-blue-600 hover:bg-blue-100 rounded transition-colors"
                  title="复制"
                >
                  {copiedPrompt === 'image' ? (
                    <Check className="w-4 h-4" />
                  ) : (
                    <Copy className="w-4 h-4" />
                  )}
                </button>
                {onUpdate && (
                  <button
                    onClick={() => setEditingPrompt({ type: 'image', prompt: imagePrompt })}
                    className="p-1.5 text-blue-600 hover:bg-blue-100 rounded transition-colors"
                    title="编辑"
                  >
                    <Edit2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
          </div>
          <div className="p-4 bg-white">
            <pre className="text-sm text-gray-700 whitespace-pre-wrap font-sans leading-relaxed">
              {imagePrompt}
            </pre>
          </div>
        </div>
      )}

      {/* Video Prompt */}
      {videoPrompt && (
        <div className="border border-purple-200 rounded-lg overflow-hidden">
          <div className="px-4 py-3 bg-purple-50 border-b border-purple-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Video className="w-4 h-4 text-purple-600" />
                <h3 className="text-sm font-medium text-purple-900">视频提示词</h3>
                <span className="text-xs px-2 py-0.5 bg-purple-100 text-purple-700 rounded">
                  动作描述
                </span>
              </div>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => handleCopy(videoPrompt, 'video')}
                  className="p-1.5 text-purple-600 hover:bg-purple-100 rounded transition-colors"
                  title="复制"
                >
                  {copiedPrompt === 'video' ? (
                    <Check className="w-4 h-4" />
                  ) : (
                    <Copy className="w-4 h-4" />
                  )}
                </button>
                {onUpdate && (
                  <button
                    onClick={() => setEditingPrompt({ type: 'video', prompt: videoPrompt })}
                    className="p-1.5 text-purple-600 hover:bg-purple-100 rounded transition-colors"
                    title="编辑"
                  >
                    <Edit2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
          </div>
          <div className="p-4 bg-white">
            <pre className="text-sm text-gray-700 whitespace-pre-wrap font-sans leading-relaxed">
              {videoPrompt}
            </pre>
          </div>
        </div>
      )}

      {/* Prompt Editor Modal */}
      {editingPrompt && (
        <PromptEditor
          initialPrompt={editingPrompt.prompt}
          title={`编辑${editingPrompt.type === 'image' ? '图像' : '视频'}提示词`}
          type={editingPrompt.type}
          onSave={handleSavePrompt}
          onClose={() => setEditingPrompt(null)}
          onOptimize={onOptimize ? handleOptimizePrompt : undefined}
        />
      )}
    </div>
  );
}
