'use client';

import React, { useRef, useEffect, useState } from 'react';
import { Copy, Check } from 'lucide-react';
import { AppNodeData } from '../../types/node';
import { SecureVideo } from '../components/SecureVideo';
import { SecureImage } from '@/components/common/SecureImage';
import { TextPlaceholder, MediaPlaceholder } from '../components/MediaPlaceholder';

interface InfoDisplayRendererProps {
    data: AppNodeData;
    title?: string;
}

export const InfoDisplayRenderer = ({ data, title }: InfoDisplayRendererProps) => {
    const info = data.assetInfo || {};
    const containerRef = useRef<HTMLDivElement>(null);
    const [mediaLoaded, setMediaLoaded] = useState(false);
    const [copiedPrompt, setCopiedPrompt] = useState<string | null>(null);
    
    // Check if content is loading (placeholder state)
    const isLoading = !info.name && !title;

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

    useEffect(() => {
        const container = containerRef.current;
        if (!container) return;
        
        const handleWheel = (e: WheelEvent) => {
            e.stopPropagation();
        };
        
        container.addEventListener('wheel', handleWheel, { passive: false });
        
        return () => {
            container.removeEventListener('wheel', handleWheel);
        };
    }, []);

    return (
        <div 
            ref={containerRef}
            className="w-full h-full p-6 flex flex-col gap-4 overflow-y-auto custom-scrollbar"
        >
            {isLoading ? (
                // Show placeholder while loading
                <div className="flex flex-col gap-4">
                    <TextPlaceholder />
                    <TextPlaceholder />
                    <div className="mt-4 p-3 bg-white/5 rounded-lg">
                        <TextPlaceholder />
                    </div>
                </div>
            ) : (
                <>
                    <div className="flex flex-col gap-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">名称</span>
                        <span className="text-sm text-foreground font-medium">{info.name || title || '无标题'}</span>
                    </div>
            
            {/* Basic Info Grid */}
            <div className="grid grid-cols-2 gap-3">
                <div className="flex flex-col gap-1">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">类型</span>
                    <span className="text-xs text-muted-foreground capitalize">{info.type || '未知'}</span>
                </div>
            </div>

            {/* Character Specific */}
            {info.type === 'character' && (
                <div className="grid grid-cols-2 gap-3 p-3 bg-white/5 rounded-lg border border-white/5">
                    {info.gender && (
                        <div className="flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">性别</span>
                            <span className="text-xs text-muted-foreground">{info.gender}</span>
                        </div>
                    )}
                    {info.age && (
                        <div className="flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">年龄</span>
                            <span className="text-xs text-muted-foreground">{info.age}</span>
                        </div>
                    )}
                    {info.role && (
                        <div className="col-span-2 flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">角色定位</span>
                            <span className="text-xs text-muted-foreground">{info.role}</span>
                        </div>
                    )}
                     {info.appearance && (
                        <div className="col-span-2 flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">外貌特征</span>
                            <p className="text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap">{info.appearance}</p>
                        </div>
                    )}
                </div>
            )}
            
            {/* Scene Specific */}
            {info.type === 'scene' && (
                <div className="grid grid-cols-2 gap-3 p-3 bg-white/5 rounded-lg border border-white/5">
                    {info.location && (
                        <div className="col-span-2 flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">地点</span>
                            <span className="text-xs text-muted-foreground">{info.location}</span>
                        </div>
                    )}
                    {info.timeOfDay && (
                        <div className="flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">时间</span>
                            <span className="text-xs text-muted-foreground">{info.timeOfDay}</span>
                        </div>
                    )}
                    {info.atmosphere && (
                        <div className="flex flex-col gap-1">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">氛围</span>
                            <span className="text-xs text-muted-foreground">{info.atmosphere}</span>
                        </div>
                    )}
                </div>
            )}

            {/* Storyboard/Shot Specific */}
            {(info.type === 'storyboard' || info.shot || info.duration || info.cameraMovement) && (
                <div className="flex flex-col gap-3">
                    <div className="grid grid-cols-2 gap-3 p-3 bg-white/5 rounded-lg border border-white/5">
                        {info.shot && (
                            <div className="flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">景别</span>
                                <span className="text-xs text-muted-foreground">{info.shot}</span>
                            </div>
                        )}
                        {info.duration && (
                            <div className="flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">时长</span>
                                <span className="text-xs text-muted-foreground">{info.duration}</span>
                            </div>
                        )}
                        {info.location && (
                            <div className="col-span-2 flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">地点</span>
                                <span className="text-xs text-muted-foreground">{info.location}</span>
                            </div>
                        )}
                        {info.time && (
                            <div className="flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">时间</span>
                                <span className="text-xs text-muted-foreground">{info.time}</span>
                            </div>
                        )}
                        {info.cameraMovement && (
                            <div className="col-span-2 flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">运镜</span>
                                <span className="text-xs text-muted-foreground">{info.cameraMovement}</span>
                            </div>
                        )}
                        {info.voiceover && (
                            <div className="col-span-2 flex flex-col gap-1">
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">旁白/台词</span>
                                <p className="text-xs text-muted-foreground italic">&quot;{info.voiceover}&quot;</p>
                            </div>
                        )}
                    </div>

                    {/* Related Assets */}
                    {(info.resolvedScene || (info.resolvedCharacters && info.resolvedCharacters.length > 0) || (info.resolvedProps && info.resolvedProps.length > 0)) && (
                        <div className="flex flex-col gap-2 p-3 bg-white/5 rounded-lg border border-white/5">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1">关联资产</span>
                            
                            {info.resolvedScene && (
                                <div className="flex flex-col gap-1 mb-2">
                                    <span className="text-[10px] text-muted-foreground/70">场景</span>
                                    <div className="flex items-center gap-2">
                                        <span className="text-xs text-foreground bg-white/10 px-2 py-1 rounded">{info.resolvedScene.name}</span>
                                    </div>
                                </div>
                            )}

                            {info.resolvedCharacters && info.resolvedCharacters.length > 0 && (
                                <div className="flex flex-col gap-1 mb-2">
                                    <span className="text-[10px] text-muted-foreground/70">角色</span>
                                    <div className="flex flex-wrap gap-1">
                                        {info.resolvedCharacters.map((char: any) => (
                                            <span key={char.id} className="text-xs text-foreground bg-white/10 px-2 py-1 rounded">{char.name}</span>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {info.resolvedProps && info.resolvedProps.length > 0 && (
                                <div className="flex flex-col gap-1">
                                    <span className="text-[10px] text-muted-foreground/70">道具</span>
                                    <div className="flex flex-wrap gap-1">
                                        {info.resolvedProps.map((prop: any) => (
                                            <span key={prop.id} className="text-xs text-foreground bg-white/10 px-2 py-1 rounded">{prop.name}</span>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}

            {info.desc && (
                <div className="flex flex-col gap-1">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">描述</span>
                    <p className="text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap">{info.desc}</p>
                </div>
            )}

            {/* AI Generated Prompts for Assets */}
            {info.imagePrompt && (info.type === 'character' || info.type === 'scene' || info.type === 'prop') && (
                <div className="flex flex-col gap-1 p-3 bg-blue-500/10 rounded-lg border border-blue-500/20">
                    <div className="flex items-center justify-between mb-1">
                        <div className="flex items-center gap-2">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-blue-400">AI 生图提示词</span>
                            {(info.type === 'character' || info.type === 'prop') && (
                                <span className="text-[9px] px-1.5 py-0.5 bg-blue-500/20 text-blue-300 rounded">白底图</span>
                            )}
                            {info.type === 'scene' && (
                                <span className="text-[9px] px-1.5 py-0.5 bg-green-500/20 text-green-300 rounded">纯场景</span>
                            )}
                        </div>
                        <button
                            onClick={() => handleCopyPrompt(info.imagePrompt, 'imagePrompt')}
                            className="p-1.5 hover:bg-blue-500/20 rounded transition-colors"
                            title="复制提示词"
                        >
                            {copiedPrompt === 'imagePrompt' ? (
                                <Check size={14} className="text-green-400" />
                            ) : (
                                <Copy size={14} className="text-blue-400" />
                            )}
                        </button>
                    </div>
                    <p className="text-xs text-blue-200/80 leading-relaxed whitespace-pre-wrap font-mono">{info.imagePrompt}</p>
                </div>
            )}

            {/* Original Text for Storyboards */}
            {info.originalText && (info.type === 'storyboard' || info.shot) && (
                <div className="flex flex-col gap-1 p-3 bg-gray-500/10 rounded-lg border border-gray-500/20">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400">原文</span>
                    <p className="text-xs text-gray-300/80 leading-relaxed whitespace-pre-wrap">{info.originalText}</p>
                </div>
            )}

            {/* Merge Image Prompt for Storyboards */}
            {info.mergeImagePrompt && (info.type === 'storyboard' || info.shot) && (
                <div className="flex flex-col gap-1 p-3 bg-blue-500/10 rounded-lg border border-blue-500/20">
                    <div className="flex items-center justify-between mb-1">
                        <div className="flex items-center gap-2">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-blue-400">融图提示词</span>
                            <span className="text-[9px] px-1.5 py-0.5 bg-blue-500/20 text-blue-300 rounded">图像生成</span>
                        </div>
                        <button
                            onClick={() => handleCopyPrompt(info.mergeImagePrompt, 'mergeImagePrompt')}
                            className="p-1.5 hover:bg-blue-500/20 rounded transition-colors"
                            title="复制提示词"
                        >
                            {copiedPrompt === 'mergeImagePrompt' ? (
                                <Check size={14} className="text-green-400" />
                            ) : (
                                <Copy size={14} className="text-blue-400" />
                            )}
                        </button>
                    </div>
                    <p className="text-xs text-blue-200/80 leading-relaxed whitespace-pre-wrap font-mono">{info.mergeImagePrompt}</p>
                </div>
            )}

            {/* Video Prompt for Storyboards */}
            {info.videoPrompt && (info.type === 'storyboard' || info.shot) && (
                <div className="flex flex-col gap-1 p-3 bg-purple-500/10 rounded-lg border border-purple-500/20">
                    <div className="flex items-center justify-between mb-1">
                        <div className="flex items-center gap-2">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-purple-400">视频提示词</span>
                            <span className="text-[9px] px-1.5 py-0.5 bg-purple-500/20 text-purple-300 rounded">动作描述</span>
                        </div>
                        <button
                            onClick={() => handleCopyPrompt(info.videoPrompt, 'videoPrompt')}
                            className="p-1.5 hover:bg-purple-500/20 rounded transition-colors"
                            title="复制提示词"
                        >
                            {copiedPrompt === 'videoPrompt' ? (
                                <Check size={14} className="text-green-400" />
                            ) : (
                                <Copy size={14} className="text-purple-400" />
                            )}
                        </button>
                    </div>
                    <p className="text-xs text-purple-200/80 leading-relaxed whitespace-pre-wrap font-mono">{info.videoPrompt}</p>
                </div>
            )}
            {info.tags && info.tags.length > 0 && (
                <div className="flex flex-col gap-1">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">标签</span>
                    <div className="flex flex-wrap gap-1">
                        {info.tags.map((tag: string, i: number) => (
                            <span key={i} className="px-1.5 py-0.5 bg-white/5 rounded text-[10px] text-muted-foreground border border-white/5">{tag}</span>
                        ))}
                    </div>
                </div>
            )}
             {(info.imageUrl || (info.videoUrls && info.videoUrls.length > 0)) && (
                <div className="mt-2 rounded-lg overflow-hidden border border-white/10 bg-black/20 shrink-0 self-start relative">
                    {!mediaLoaded && (
                        <div className="absolute inset-0">
                            <MediaPlaceholder
                                type={info.videoUrls ? 'video' : 'image'}
                                message="加载媒体中..."
                                animated={true}
                            />
                        </div>
                    )}
                    {info.videoUrls && info.videoUrls.length > 0 ? (
                        <SecureVideo 
                            src={info.videoUrls[0]} 
                            className="w-auto h-48 object-cover" 
                            controls 
                            onLoadedData={() => setMediaLoaded(true)}
                            onError={() => setMediaLoaded(true)}
                        />
                    ) : (
                         <SecureImage 
                            src={info.imageUrl} 
                            className="w-auto h-48 object-cover" 
                            alt={info.name}
                            onLoad={() => setMediaLoaded(true)}
                            onError={() => setMediaLoaded(true)}
                        />
                    )}
                </div>
             )}
                </>
            )}
        </div>
    );
};
