'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, Search, ArrowUpDown, ArrowUp, ArrowDown, ArrowLeft,Film, Clapperboard, ChevronRight, ChevronDown } from 'lucide-react';
import { cn } from '@/utils';
import { SecureImage } from '@/components/common/SecureImage';
import { Storyboard, Episode } from '@/types';
import { EmptyState } from '@/components/ui/empty-state';

interface StoryboardPanelProps {
    onClose: () => void;
    projectStoryboards?: Storyboard[];
    projectEpisodes?: Episode[];
    onAddToCanvas?: (item: any) => void;
    onHistoryItemClick?: (item: any) => void;
    onContextMenu?: (e: React.MouseEvent, item: any) => void;
}

export const StoryboardPanel = ({
    onClose,
    projectStoryboards = [],
    projectEpisodes = [],
    onAddToCanvas,
    onHistoryItemClick,
    onContextMenu
}: StoryboardPanelProps) => {
    const [viewedStoryboard, setViewedStoryboard] = useState<Storyboard | null>(null);
    const [expandedEpisodes, setExpandedEpisodes] = useState<Record<string, boolean>>({});
    const [previewItem, setPreviewItem] = useState<{ type: 'image' | 'video', src: string, title: string } | null>(null);
    
    // Search & Sort State
    const [searchQuery, setSearchQuery] = useState('');
    const [sortOrder, setSortOrder] = useState<'default' | 'shot_asc' | 'shot_desc'>('default');

    const displayItems = useMemo(() => {
        return projectStoryboards;
    }, [projectStoryboards]);

    // Apply Search and Sort
    const filteredAndSortedItems = useMemo(() => {
        let items = [...displayItems];

        // 1. Search
        if (searchQuery.trim()) {
            const q = searchQuery.toLowerCase();
            items = items.filter(item => {
                const text = `${item.shot} ${item.desc || ''} ${item.originalText || ''}`;
                return text.toLowerCase().includes(q);
            });
        }

        // 2. Sort
        if (sortOrder !== 'default') {
            items.sort((a, b) => {
                const shotA = a.shot || '';
                const shotB = b.shot || '';
                
                if (sortOrder === 'shot_asc') {
                    return shotA.localeCompare(shotB, undefined, { numeric: true });
                } else {
                    return shotB.localeCompare(shotA, undefined, { numeric: true });
                }
            });
        } else {
            // Default sort: Episode Order + Shot Order
            items.sort((a, b) => {
                // Assuming we might want to sort by episode first if we had episode info readily available for sort
                // For now, just rely on shot order or existing order
                return a.order - b.order;
            });
        }

        return items;
    }, [displayItems, searchQuery, sortOrder]);

    // Expand all episodes by default
    useEffect(() => {
        if (projectEpisodes.length > 0) {
            setExpandedEpisodes(prev => {
                const next = { ...prev };
                let hasChanges = false;
                projectEpisodes.forEach(ep => {
                    if (next[ep.id] === undefined) {
                        next[ep.id] = true;
                        hasChanges = true;
                    }
                });
                return hasChanges ? next : prev;
            });
        }
    }, [projectEpisodes]);

    const groupedItems = useMemo(() => {
        const groups: Record<string, Storyboard[]> = {};
        const uncategorized: Storyboard[] = [];

        filteredAndSortedItems.forEach(item => {
            if (item.episodeId) {
                if (!groups[item.episodeId]) groups[item.episodeId] = [];
                groups[item.episodeId].push(item);
            } else {
                uncategorized.push(item);
            }
        });

        return { groups, uncategorized };
    }, [filteredAndSortedItems]);

    const viewedStoryboardItems = useMemo(() => {
        if (!viewedStoryboard) return [];
        const items: { id: string, type: 'image' | 'video', src: string, title: string }[] = [];
        if (viewedStoryboard.imageUrls) viewedStoryboard.imageUrls.forEach((url, i) => items.push({ id: `${viewedStoryboard.id}-img-${i}`, type: 'image', src: url, title: `Shot ${viewedStoryboard.shot} (Image ${i+1})` }));
        if (viewedStoryboard.videoUrls) viewedStoryboard.videoUrls.forEach((url, i) => items.push({ id: `${viewedStoryboard.id}-vid-${i}`, type: 'video', src: url, title: `Shot ${viewedStoryboard.shot} (Video ${i+1})` }));
        return items;
    }, [viewedStoryboard]);

    const renderStoryboardItem = (item: any) => {
        // Check if it's a raw media item (from detail view) or a Storyboard object
        const isStoryboardObject = 'shot' in item && 'id' in item;
        
        if (isStoryboardObject) {
            const storyboard = item as Storyboard;
            const hasVideo = storyboard.videoUrls && storyboard.videoUrls.length > 0;
            const videoUrl = hasVideo ? storyboard.videoUrls![0] : undefined;
            // Fallback to first image in imageUrls
            const displayImage = storyboard.imageUrls && storyboard.imageUrls.length > 0 ? storyboard.imageUrls[0] : undefined;

            return (
                <div 
                    key={storyboard.id} 
                    className="flex gap-3 p-2 rounded-lg hover:bg-white/5 transition-all cursor-pointer group border border-transparent hover:border-white/10 active:scale-[0.99]"
                    draggable={true}
                    onDragStart={(e) => {
                        const src = videoUrl || displayImage;
                        if (src) {
                            e.dataTransfer.setData('application/assetSrc', src);
                            e.dataTransfer.setData('application/assetType', videoUrl ? 'video' : 'image');
                            e.dataTransfer.setData('application/nodeTitle', `Shot ${storyboard.shot}`);
                            e.dataTransfer.effectAllowed = 'copy';
                        }
                    }}
                    onContextMenu={(e) => onContextMenu?.(e, storyboard)}
                    onClick={() => setViewedStoryboard(storyboard)}
                    onMouseEnter={() => {
                        if (videoUrl) {
                            setPreviewItem({ type: 'video', src: videoUrl, title: `#${storyboard.order} ${storyboard.shot}` });
                        } else if (displayImage) {
                            setPreviewItem({ type: 'image', src: displayImage, title: `#${storyboard.order} ${storyboard.shot}` });
                        }
                    }}
                    onMouseLeave={() => setPreviewItem(null)}
                >
                    {/* Thumbnail */}
                    <div className="w-24 aspect-video bg-black/20 rounded-md overflow-hidden relative flex-shrink-0 border border-white/5">
                        {displayImage ? (
                            <SecureImage src={displayImage} alt={`#${storyboard.order} ${storyboard.shot}`} className="w-full h-full object-cover" draggable={false} />
                        ) : (
                            <div className="w-full h-full flex items-center justify-center bg-white/5 text-muted-foreground">
                                <Clapperboard size={14} className="opacity-30" />
                            </div>
                        )}
                        
                        {/* Shot Badge */}
                        <div className="absolute top-0.5 left-0.5 px-1 py-0.5 bg-black/60 backdrop-blur-md rounded text-[8px] text-white/90 font-mono font-bold pointer-events-none border border-white/10">
                            #{storyboard.order}
                        </div>

                         {/* Video Indicator */}
                        {hasVideo && (
                            <div className="absolute top-0.5 right-0.5 p-0.5 bg-black/60 backdrop-blur-md rounded-full text-white/90 pointer-events-none border border-white/10">
                                <Film size={6} />
                            </div>
                        )}
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0 flex flex-col justify-center gap-0.5">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-medium text-white/90 truncate">{storyboard.shot}</span>
                            {/* Status or Time could go here */}
                        </div>
                        <p className="text-[10px] text-muted-foreground line-clamp-2 leading-relaxed">
                            {storyboard.desc || storyboard.originalText || 'No description'}
                        </p>
                    </div>
                </div>
            );
        } else {
            // Media Item (Detail View)
            return (
                <div 
                    key={item.id} 
                    className="aspect-square rounded-xl overflow-hidden cursor-grab active:cursor-grabbing border border-white/5 hover:border-cyan-500/50 transition-colors group relative shadow-md bg-black/20"
                    draggable={true}
                    onDragStart={(e) => {
                        e.dataTransfer.setData('application/assetSrc', item.src);
                        e.dataTransfer.setData('application/assetType', item.type);
                        e.dataTransfer.setData('application/nodeTitle', item.title || 'Media');
                        e.dataTransfer.effectAllowed = 'copy';
                    }}
                    onClick={() => onHistoryItemClick?.({ type: item.type, src: item.src })}
                    onMouseEnter={() => setPreviewItem({ type: item.type, src: item.src, title: item.title || 'Untitled' })}
                    onMouseLeave={() => setPreviewItem(null)}
                >
                    {item.type === 'image' ? (
                        <SecureImage src={item.src} alt={item.title} className="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" draggable={false} />
                    ) : (
                        <video 
                            src={item.src} 
                            className="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" 
                            draggable={false}
                            muted
                            loop
                            playsInline
                        />
                    )}
                    <div className="absolute top-1 right-1 px-1.5 py-0.5 rounded-full bg-black/60 backdrop-blur-md text-[8px] font-bold text-white/70 pointer-events-none">
                        {item.type === 'image' ? 'IMG' : 'MOV'}
                    </div>
                </div>
            );
        }
    };

    return (
        <>
            <div className="p-4 border-b border-white/5 flex flex-col gap-3 bg-white/5">
                <div className="flex justify-between items-center">
                    {viewedStoryboard ? (
                        <button onClick={() => setViewedStoryboard(null)} className="flex items-center gap-2 text-muted-foreground hover:text-white transition-colors group">
                             <div className="p-1 rounded-full bg-white/5 group-hover:bg-white/10">
                                <ArrowLeft size={12} />
                             </div>
                             <span className="text-xs font-bold truncate max-w-[180px]">#{viewedStoryboard.order} {viewedStoryboard.shot}</span>
                        </button>
                    ) : (
                        <>
                            <button onClick={onClose}><X size={14} className="text-muted-foreground hover:text-white" /></button>
                            <span className="text-xs font-bold uppercase tracking-widest text-foreground/50">分镜库</span>
                        </>
                    )}
                </div>

                {/* Hide filters when in detail view */}
                {!viewedStoryboard && (
                    <div className="flex gap-2">
                        <div className="relative flex-1">
                            <Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                            <input 
                                type="text" 
                                placeholder="搜索分镜..." 
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="w-full bg-black/20 border border-white/5 rounded-lg py-1.5 pl-8 pr-2 text-xs text-white placeholder:text-muted-foreground focus:outline-none focus:border-white/20 transition-colors"
                            />
                            {searchQuery && (
                                <button 
                                    onClick={() => setSearchQuery('')}
                                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-white"
                                >
                                    <X size={10} />
                                </button>
                            )}
                        </div>
                        <button 
                            onClick={() => {
                                if (sortOrder === 'default') setSortOrder('shot_asc');
                                else if (sortOrder === 'shot_asc') setSortOrder('shot_desc');
                                else setSortOrder('default');
                            }}
                            className={cn(
                                "w-8 flex items-center justify-center rounded-lg border border-white/5 transition-colors",
                                sortOrder !== 'default' ? "bg-white/10 text-white" : "bg-black/20 text-muted-foreground hover:text-white"
                            )}
                            title="排序: 默认 -> 镜头号(1-9) -> 镜头号(9-1)"
                        >
                            {sortOrder === 'default' ? <ArrowUpDown size={12} /> : 
                            sortOrder === 'shot_asc' ? <ArrowDown size={12} className="rotate-0 transition-transform" /> : 
                            <ArrowUp size={12} />
                            }
                        </button>
                    </div>
                )}
            </div>
            
            <div className="flex-1 overflow-y-auto p-2 custom-scrollbar space-y-2 relative">
                {viewedStoryboard ? (
                    // Detail View Grid
                    <div className="grid grid-cols-2 gap-2 p-1 animate-in fade-in slide-in-from-right-4 duration-300">
                        {viewedStoryboardItems.map(renderStoryboardItem)}
                        {viewedStoryboardItems.length === 0 && (
                            <div className="col-span-2 flex flex-col items-center justify-center py-10 text-muted-foreground opacity-60">
                                <Clapperboard size={32} className="mb-2 opacity-50" />
                                <span className="text-[10px]">无相关媒体</span>
                            </div>
                        )}
                    </div>
                ) : (
                    // Main List View
                    <>
                        {filteredAndSortedItems.length === 0 ? (
                            <EmptyState 
                                icon={searchQuery ? Search : Clapperboard}
                                title={searchQuery ? "未找到相关分镜" : "暂无分镜"}
                                description={searchQuery ? "换个关键词试试？" : "请先在脚本中生成分镜"}
                                className="py-10 opacity-60"
                                textClassName="text-[10px] tracking-widest uppercase"
                            />
                        ) : (
                            <div className="space-y-4 p-1">
                                {projectEpisodes.map(ep => {
                                    const items = groupedItems.groups[ep.id];
                                    if (!items || items.length === 0) return null;
                                    const isExpanded = expandedEpisodes[ep.id] ?? true;

                                    return (
                                        <div key={ep.id} className="space-y-1">
                                            <button 
                                                onClick={() => setExpandedEpisodes(prev => ({ ...prev, [ep.id]: !isExpanded }))}
                                                className="flex items-center gap-2 w-full text-left px-1 py-1 text-xs font-medium text-muted-foreground hover:text-white transition-colors"
                                            >
                                                {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
                                                <span>{ep.title || `Episode ${ep.order}`}</span>
                                                <span className="text-[10px] opacity-50 ml-auto">{items.length}</span>
                                            </button>
                                            
                                            {isExpanded && (
                                                <div className="flex flex-col gap-1 animate-in slide-in-from-top-2 duration-200">
                                                    {items.map((item, idx) => (
                                                        <React.Fragment key={item.id}>
                                                            {renderStoryboardItem(item)}
                                                        </React.Fragment>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                    );
                                })}

                                {/* Uncategorized */}
                                {groupedItems.uncategorized.length > 0 && (
                                    <div className="space-y-1">
                                        <div className="px-1 py-1 text-xs font-medium text-muted-foreground">
                                            未分类
                                        </div>
                                        <div className="flex flex-col gap-1">
                                            {groupedItems.uncategorized.map((item, idx) => (
                                                <React.Fragment key={item.id}>
                                                    {renderStoryboardItem(item)}
                                                </React.Fragment>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}
                    </>
                )}
            </div>
            
            {/* Large Preview Overlay */}
            {previewItem && createPortal(
                <div className="fixed left-[26rem] top-1/2 -translate-y-1/2 w-[400px] h-[400px] bg-black/90 border border-white/20 rounded-xl shadow-2xl z-[9999] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200 pointer-events-none">
                    <div className="flex-1 relative bg-black/50 flex items-center justify-center overflow-hidden">
                        {previewItem.type === 'image' ? (
                            <SecureImage 
                                src={previewItem.src} 
                                alt={previewItem.title} 
                                className="w-full h-full object-contain" 
                            />
                        ) : (
                            <video 
                                src={previewItem.src} 
                                className="w-full h-full object-contain" 
                                autoPlay 
                                muted 
                                loop 
                                playsInline 
                            />
                        )}
                    </div>
                    <div className="p-3 bg-black/80 border-t border-white/10 backdrop-blur-md">
                        <div className="flex items-center justify-between mb-1">
                            <span className="text-xs font-bold text-white truncate max-w-[280px]">
                                {previewItem.title}
                            </span>
                            <span className="text-[10px] px-1.5 py-0.5 rounded bg-white/10 text-white/70 font-mono">
                                {previewItem.type === 'image' ? 'IMAGE' : 'VIDEO'}
                            </span>
                        </div>
                    </div>
                </div>,
                document.body
            )}
        </>
    );
};
