'use client';

import React, { useRef, useState, memo } from 'react';
import { Video, Image as ImageIcon, AlertCircle } from 'lucide-react';
import { AppNodeData, InputAsset } from '../../types/node';
import { SecureVideo } from '../components/SecureVideo';
import { SecureImage } from '@/components/common/SecureImage';
import { SceneDirectorOverlay } from '../components/VideoModules';
import { MediaPlaceholder } from '../components/MediaPlaceholder';
import { NodeLoadingOverlay, NodeLoadingAccent } from '../components/NodeLoadingOverlay';
import { cn } from '@/utils';

interface MediaDisplayRendererProps {
    type: string;
    loadingAccent?: NodeLoadingAccent;
    image?: string;
    videoUri?: string;
    images?: string[];
    videoUris?: string[];
    content?: string;
    title?: string;
    error?: string;
    generationMode?: string;
    croppedFrame?: string;
    inputAssets?: InputAsset[];
    isWorking: boolean;
    onExpand?: () => void;
    icon?: React.ElementType;
    update?: (data: Partial<AppNodeData>) => void;
    onCropRequest?: (src: string) => void;
    onContextMenu?: (e: React.MouseEvent, type: 'image' | 'video', src: string) => void;
}

export const MediaDisplayRenderer = memo(({ 
    type,
    loadingAccent = 'cyan',
    image,
    videoUri,
    images,
    videoUris,
    content,
    title,
    error,
    generationMode,
    croppedFrame,
    inputAssets,
    isWorking, 
    onExpand, 
    icon: NodeIcon, 
    update, 
    onCropRequest, 
    onContextMenu 
}: MediaDisplayRendererProps) => {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const mediaRef = useRef<HTMLVideoElement | null>(null);
    const [showImageGrid, setShowImageGrid] = useState(false);
    const [imageLoaded, setImageLoaded] = useState(false);
    const [videoLoaded, setVideoLoaded] = useState(false);
    
    // Determine content type and existence
    const isVideoNode = type.includes('VIDEO');
    const hasImage = !!image;
    const hasVideo = !!videoUri;
    const hasContent = hasImage || hasVideo || (images && images.length > 0) || (videoUris && videoUris.length > 0);
    
    // Check if content is a placeholder (from progressive loading)
    const isPlaceholder = hasContent && (
        (hasImage && image === undefined) ||
        (hasVideo && videoUri === undefined) ||
        (content === '[Loading...]')
    );

    const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
         const file = e.target.files?.[0];
         if (!file || !update) return;
         
         const reader = new FileReader();
         reader.onload = (e) => {
             const result = e.target?.result as string;
             if (file.type.startsWith('video/')) {
                 update({ videoUri: result });
             } else {
                 update({ image: result });
             }
         };
         reader.readAsDataURL(file);
    };

    const handleMouseEnter = () => {
        if ((images?.length || 0) > 1 || (videoUris?.length || 0) > 1) {
            setShowImageGrid(true);
        }
        if (mediaRef.current) {
            mediaRef.current.play().catch(() => {
                // Ignore auto-play errors (e.g. user hasn't interacted with document)
            });
        }
    };

    const handleMouseLeave = () => {
        setShowImageGrid(false);
        if (mediaRef.current) {
            mediaRef.current.pause();
            mediaRef.current.currentTime = 0; // Optional: Reset to start
        }
    };

    // Empty State — 使用 left/top 50% + translate 保证图标与文案在节点内严格居中，避免 flex 受父级影响
    if (!hasContent || isPlaceholder) {
        return (
            <div className="absolute inset-0 text-foreground">
                {isPlaceholder && !isWorking ? (
                    <div className="absolute inset-0 flex flex-col items-center justify-center gap-3">
                        <MediaPlaceholder
                            type={isVideoNode ? 'video' : 'image'}
                            message="加载中..."
                            animated={true}
                        />
                    </div>
                ) : isPlaceholder && isWorking ? (
                    <NodeLoadingOverlay message="生成中..." accent={loadingAccent} />
                ) : (
                    <>
                        <div
                            className="absolute left-1/2 top-1/2 flex flex-col items-center gap-3 -translate-x-1/2 -translate-y-1/2"
                            style={{ width: 'max-content' }}
                        >
                            <div
                                className="w-20 h-20 flex-shrink-0 rounded-[28px] bg-white/5 border border-white/5 flex items-center justify-center cursor-pointer hover:bg-white/10 hover:scale-105 transition-all duration-300 shadow-inner"
                                onClick={() => !isWorking && update && fileInputRef.current?.click()}
                            >
                                {NodeIcon ? <NodeIcon size={32} className="opacity-50" /> : (isVideoNode ? <Video size={32} className="opacity-50" /> : <ImageIcon size={32} className="opacity-50" />)}
                            </div>
                            <span className="text-[11px] font-bold uppercase tracking-[0.2em] opacity-40 text-center whitespace-nowrap">
                                {isWorking ? "生成中..." : (update ? "拖拽或上传" : "等待生成")}
                            </span>
                        </div>
                        {update && (
                            <input
                                type="file"
                                ref={fileInputRef}
                                className="hidden"
                                accept={isVideoNode ? "video/*" : "image/*"}
                                onChange={handleUpload}
                            />
                        )}
                        {isWorking && <NodeLoadingOverlay message="生成中..." accent={loadingAccent} />}
                    </>
                )}
            </div>
        );
    }

    // Main Content Display
    return (
        <div 
            className="w-full h-full group/media relative overflow-hidden bg-card"
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
        >
            {hasVideo ? (
                <>
                    {/* Show placeholder while video is loading */}
                    {!videoLoaded && (
                        <MediaPlaceholder
                            type="video"
                            message="加载视频中..."
                            animated={true}
                        />
                    )}
                    <SecureVideo 
                        ref={mediaRef}
                        src={videoUri || ''}
                        className={cn(
                            "w-full h-full object-cover bg-card nopan",
                            !videoLoaded && "opacity-0"
                        )}
                        muted
                        loop
                        controls={false}
                        playsInline
                        crossOrigin="anonymous"
                        style={{ filter: showImageGrid ? 'blur(10px)' : 'none' }}
                        onLoadedData={() => setVideoLoaded(true)}
                        onError={() => setVideoLoaded(true)} // Show content even on error
                    />
                    <SceneDirectorOverlay 
                        visible={type === 'VIDEO_GENERATOR' && generationMode === 'CUT'}
                        videoRef={mediaRef}
                        onCrop={() => {
                            const vid = mediaRef.current;
                            if (vid) {
                                const canvas = document.createElement('canvas');
                                canvas.width = vid.videoWidth;
                                canvas.height = vid.videoHeight;
                                const ctx = canvas.getContext('2d');
                                if (ctx) {
                                    ctx.drawImage(vid, 0, 0);
                                    const fullFrame = canvas.toDataURL('image/png');
                                    
                                    if (onCropRequest) {
                                        onCropRequest(fullFrame);
                                    } else if (update) {
                                        // Fallback if no cropper available
                                        update({ croppedFrame: fullFrame });
                                    }
                                }
                            }
                        }} 
                        onTimeHover={() => {}} 
                    />
                </>
            ) : (
                <>
                    {/* Show placeholder while image is loading */}
                    {!imageLoaded && (
                        <MediaPlaceholder
                            type="image"
                            message="加载图片中..."
                            animated={true}
                        />
                    )}
                    <SecureImage 
                        src={image!} 
                        alt={title} 
                        className={cn(
                            "w-full h-full object-cover transition-transform duration-700 group-hover/media:scale-105 bg-card",
                            !imageLoaded && "opacity-0"
                        )}
                        style={{ filter: showImageGrid ? 'blur(10px)' : 'none' }}
                        onLoad={() => setImageLoaded(true)}
                        onError={() => setImageLoaded(true)} // Show content even on error
                    />
                </>
            )}

            {/* Frame Count Badge */}
            {(images && images.length > 1) && (
                <div className="absolute top-2 right-2 bg-black/60 backdrop-blur-md px-2 py-0.5 rounded text-[10px] text-white/90 border border-white/10 font-mono z-20">
                    {images.length} FRAMES
                </div>
            )}

            {/* Error Overlay */}
            {error && (
                <div className="absolute inset-0 bg-black/60 backdrop-blur-md flex flex-col items-center justify-center p-6 text-center z-20 animate-in fade-in duration-200">
                    <AlertCircle className="text-red-500 mb-2" />
                    <span className="text-xs text-red-200">{error}</span>
                </div>
            )}

            {isWorking && <NodeLoadingOverlay message="生成中..." accent={loadingAccent} />}

            {/* Grid View Overlay */}
            {showImageGrid && ((images && images.length > 1) || (videoUris && videoUris.length > 1)) && (
                <div className="absolute inset-0 bg-black/40 z-10 grid grid-cols-2 gap-2 p-2 animate-in fade-in duration-200">
                    {(images || videoUris || []).slice(0, 4).map((item, i) => (
                        <div 
                            key={i} 
                            className={cn(
                                "relative w-full h-full overflow-hidden rounded-lg bg-card cursor-pointer border-2 transition-all duration-200",
                                (videoUris ? item === videoUri : item === image) 
                                    ? "border-cyan-500" 
                                    : "border-transparent hover:border-white/50"
                            )}
                            onClick={(e) => {
                                e.stopPropagation();
                                if (update) {
                                    if (videoUris) update({ videoUri: item });
                                    else update({ image: item });
                                }
                            }}
                        >
                            {videoUris ? (
                                <SecureVideo 
                                    src={item} 
                                    className="w-full h-full object-cover opacity-80 hover:opacity-100 transition-opacity" 
                                    autoPlay 
                                    loop 
                                    muted 
                                    playsInline
                                />
                            ) : (
                                <SecureImage 
                                    src={item} 
                                    alt={`Grid ${i}`} 
                                    className="w-full h-full object-cover opacity-80 hover:opacity-100 transition-opacity" 
                                    onSrcRefreshed={(newUrl) => {
                                        if (update && images) {
                                            const newImages = [...images];
                                            newImages[i] = newUrl;
                                            update({ images: newImages });
                                            // If this was also the main displayed image, update it too
                                            if (image === item) {
                                                update({ image: newUrl });
                                            }
                                        }
                                    }}
                                />
                            )}
                            {i === 3 && (images || videoUris || []).length > 4 && (
                                <div className="absolute inset-0 flex items-center justify-center bg-black/60 font-bold text-xs backdrop-blur-[1px]">
                                    +{(images || videoUris || []).length - 4}
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            {/* Cropped Frame Preview */}
            {generationMode === 'CUT' && croppedFrame && (
                <div className="absolute top-4 right-4 w-24 aspect-video bg-black/80 rounded-lg border border-purple-500/50 shadow-xl overflow-hidden z-20 hover:scale-150 transition-transform origin-top-right opacity-0 group-hover/media:opacity-100 transition-opacity duration-300">
                    <SecureImage 
                        src={croppedFrame} 
                        className="w-full h-full object-cover" 
                        onSrcRefreshed={(newUrl) => update && update({ croppedFrame: newUrl })}
                    />
                </div>
            )}

            {/* Scene Director Reference Preview (When no crop yet) */}
            {generationMode === 'CUT' && !croppedFrame && inputAssets && inputAssets.some(a => a.src) && (
                <div className="absolute top-4 right-4 w-24 aspect-video bg-black/80 rounded-lg border border-purple-500/30 border-dashed shadow-xl overflow-hidden z-20 hover:scale-150 transition-transform origin-top-right flex flex-col items-center justify-center group/preview opacity-0 group-hover/media:opacity-100 transition-opacity duration-300">
                    <div className="absolute inset-0 bg-purple-500/10 z-10"></div>
                    {(() => {
                        const asset = inputAssets!.find(a => a.src);
                        if (asset?.type === 'video') {
                            return <SecureVideo src={asset.src} className="w-full h-full object-cover opacity-60 bg-card" muted autoPlay loop />;
                        } else {
                            return <SecureImage 
                                src={asset?.src} 
                                className="w-full h-full object-cover opacity-60 bg-card" 
                                onSrcRefreshed={(newUrl) => {
                                    if (update && inputAssets) {
                                        const newAssets = inputAssets.map(a => 
                                            a.src === asset?.src ? { ...a, src: newUrl } : a
                                        );
                                        update({ inputAssets: newAssets });
                                    }
                                }}
                            />;
                        }
                    })()}
                    <span className="absolute z-20 text-[8px] font-bold text-purple-200 bg-black/50 px-1 rounded">分镜参考</span>
                </div>
            )}
        </div>
    );
});

MediaDisplayRenderer.displayName = 'MediaDisplayRenderer';
