'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, FolderHeart, Folder, FolderPlus, ImageIcon, ArrowLeft, Search, ArrowUpDown, ArrowUp, ArrowDown} from 'lucide-react';
import { cn } from '@/utils';
import { SecureImage } from '@/components/common/SecureImage';
import { Asset, Storyboard } from '@/types';
import { EmptyState } from '@/components/ui/empty-state';

interface LibraryPanelProps {
    onClose: () => void;
    sourceContext?: { id: string, type: 'asset' | 'storyboard' } | null;
    projectAssets?: Asset[];
    projectStoryboards?: Storyboard[];
    onAddToCanvas?: (item: any) => void;
    onHistoryItemClick?: (item: any) => void;
    onContextMenu?: (e: React.MouseEvent, item: any) => void;
}

export const LibraryPanel = ({
    onClose,
    sourceContext,
    projectAssets,
    projectStoryboards,
    onAddToCanvas,
    onHistoryItemClick,
    onContextMenu
}: LibraryPanelProps) => {
    const [activeLibraryTab, setActiveLibraryTab] = useState<'all' | 'associated'>('associated');
    const [activeLibraryType, setActiveLibraryType] = useState<'character' | 'scene' | 'prop' | 'other'>('character');
    const [viewedAsset, setViewedAsset] = useState<Asset | null>(null);
    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' | 'name_asc' | 'name_desc'>('default');

    // Force "associated" tab if sourceContext exists, otherwise "all"
    useEffect(() => {
        if (sourceContext) setActiveLibraryTab('associated');
        else setActiveLibraryTab('all');
    }, [sourceContext]);

    // Reset viewed asset when tab or type changes
    useEffect(() => {
        setViewedAsset(null);
    }, [activeLibraryTab, activeLibraryType]);

    const displayItems = useMemo(() => {
        if (!projectAssets) return [];
        
        // 1. If "associated" tab is active AND we have a source context
        if (activeLibraryTab === 'associated' && sourceContext) {
            if (sourceContext.type === 'asset') {
                const asset = projectAssets.find(a => a.id === sourceContext.id);
                if (asset) {
                    const images = (asset.imageUrls || []).map((url, i) => ({ id: `${asset.id}-img-${i}`, type: 'image', src: url, title: `${asset.name} (Image ${i+1})` }));
                    const videos = (asset.videoUrls || []).map((url, i) => ({ id: `${asset.id}-vid-${i}`, type: 'video', src: url, title: `${asset.name} (Video ${i+1})` }));
                    // Also include the main image if exists
                    if (asset.imageUrl && !asset.imageUrls?.includes(asset.imageUrl)) {
                        images.unshift({ id: `${asset.id}-main`, type: 'image', src: asset.imageUrl, title: asset.name });
                    }
                    return [...images, ...videos];
                }
            } else if (sourceContext.type === 'storyboard' && projectStoryboards) {
                const storyboard = projectStoryboards.find(s => s.id === sourceContext.id);
                if (storyboard) {
                     const images = (storyboard.imageUrls || []).map((url, i) => ({ id: `${storyboard.id}-img-${i}`, type: 'image', src: url, title: `Shot ${storyboard.shot} (Image ${i+1})` }));
                     const videos = (storyboard.videoUrls || []).map((url, i) => ({ id: `${storyboard.id}-vid-${i}`, type: 'video', src: url, title: `Shot ${storyboard.shot} (Video ${i+1})` }));
                     return [...images, ...videos];
                }
            }
            return [];
        }
        
        // 2. Default / All Mode: Return Assets directly
        return projectAssets.filter(a => a.type === activeLibraryType);
    }, [projectAssets, projectStoryboards, sourceContext, activeLibraryTab, activeLibraryType]);

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

        // 1. Search
        if (searchQuery.trim()) {
            const q = searchQuery.toLowerCase();
            items = items.filter(item => {
                const name = ('name' in item ? item.name : item.title) || '';
                return name.toLowerCase().includes(q);
            });
        }

        // 2. Sort
        if (sortOrder !== 'default') {
            items.sort((a, b) => {
                const nameA = ('name' in a ? a.name : a.title) || '';
                const nameB = ('name' in b ? b.name : b.title) || '';
                
                if (sortOrder === 'name_asc') {
                    return nameA.localeCompare(nameB, 'zh-CN');
                } else {
                    return nameB.localeCompare(nameA, 'zh-CN');
                }
            });
        }

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

    const viewedAssetItems = useMemo(() => {
        if (!viewedAsset) return [];
        const items = [];
        if (viewedAsset.imageUrl) items.push({ id: `${viewedAsset.id}-main`, type: 'image', src: viewedAsset.imageUrl, title: viewedAsset.name });
        if (viewedAsset.imageUrls) viewedAsset.imageUrls.forEach((url, i) => items.push({ id: `${viewedAsset.id}-img-${i}`, type: 'image', src: url, title: `${viewedAsset.name} ${i+1}` }));
        if (viewedAsset.videoUrls) viewedAsset.videoUrls.forEach((url, i) => items.push({ id: `${viewedAsset.id}-vid-${i}`, type: 'video', src: url, title: `${viewedAsset.name} ${i+1}` }));
        return items;
    }, [viewedAsset]);

    const renderAssetItem = (item: any) => {
        // Check if it's a raw media item (from associated tab or detail view) or an Asset object
        const isAssetObject = 'type' in item && ['character', 'scene', 'prop', 'other'].includes(item.type) && 'id' in item && 'name' in item;
        
        if (isAssetObject) {
            const asset = item as Asset;
            const hasVideo = asset.videoUrls && asset.videoUrls.length > 0;
            const videoUrl = hasVideo ? asset.videoUrls![0] : undefined;
            // Fallback to first image in imageUrls if imageUrl is missing
            const displayImage = asset.imageUrl || (asset.imageUrls && asset.imageUrls.length > 0 ? asset.imageUrls[0] : undefined);

            return (
                <div 
                    key={asset.id} 
                    className="aspect-square rounded-xl overflow-hidden relative group border border-white/5 bg-black/20 hover:border-white/20 transition-all cursor-pointer"
                    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', asset.name);
                            e.dataTransfer.effectAllowed = 'copy';
                        }
                    }}
                    onContextMenu={(e) => onContextMenu?.(e, asset)}
                    onClick={() => setViewedAsset(asset)}
                    onMouseEnter={() => {
                        if (videoUrl) {
                            setPreviewItem({ type: 'video', src: videoUrl, title: asset.name });
                        } else if (displayImage) {
                            setPreviewItem({ type: 'image', src: displayImage, title: asset.name });
                        }
                    }}
                    onMouseLeave={() => setPreviewItem(null)}
                >
                    {displayImage ? (
                        <SecureImage src={displayImage} alt={asset.name} className="w-full h-full object-cover transition-all duration-300" draggable={false} />
                    ) : (
                        <div className="w-full h-full flex items-center justify-center bg-white/5 text-muted-foreground">
                            <ImageIcon size={24} />
                        </div>
                    )}

                    {/* Video Preview on Hover */}
                    {videoUrl && (
                        <video 
                            src={videoUrl}
                            className="absolute inset-0 w-full h-full object-cover hidden group-hover:block"
                            autoPlay
                            muted
                            loop
                            playsInline
                        />
                    )}
                    
                    <div className="absolute bottom-0 left-0 w-full p-2 bg-gradient-to-t from-black/90 via-black/50 to-transparent text-[10px] text-white font-medium truncate z-10 pointer-events-none">
                        {asset.name}
                    </div>
                </div>
            );
        } else {
            // Media Item (Associated or 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 || 'Asset');
                        e.dataTransfer.effectAllowed = 'copy';
                    }}
                    onClick={() => onHistoryItemClick?.({ type: item.type, src: item.src })}
                    onContextMenu={(e) => onContextMenu?.(e, item)}
                    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 className="absolute bottom-0 left-0 w-full p-1.5 bg-gradient-to-t from-black/80 to-transparent text-[9px] text-foreground/90 truncate font-medium pointer-events-none">
                        {item.title || 'Untitled'}
                    </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">
                    {viewedAsset ? (
                        <button onClick={() => setViewedAsset(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]">{viewedAsset.name}</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 */}
                {!viewedAsset && (
                    <>
                        {/* Search & Sort Bar */}
                        <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('name_asc');
                                    else if (sortOrder === 'name_asc') setSortOrder('name_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="排序: 默认 -> 名称(A-Z) -> 名称(Z-A)"
                            >
                                {sortOrder === 'default' ? <ArrowUpDown size={12} /> : 
                                sortOrder === 'name_asc' ? <ArrowDown size={12} className="rotate-0 transition-transform" /> : 
                                <ArrowUp size={12} />
                                }
                            </button>
                        </div>

                        {/* Tabs: Only show if sourceContext exists to allow switching */}
                        {sourceContext && (
                            <div className="flex bg-black/20 p-1 rounded-lg">
                                <button 
                                    onClick={() => setActiveLibraryTab('associated')}
                                    className={`flex-1 flex items-center justify-center gap-2 py-1.5 text-[10px] font-bold rounded-md transition-all ${activeLibraryTab === 'associated' ? 'bg-white/10 text-foreground shadow-sm' : 'text-muted-foreground hover:text-muted-foreground'}`}
                                >
                                    <FolderHeart size={12} /> 当前关联
                                </button>
                                <button 
                                    onClick={() => setActiveLibraryTab('all')}
                                    className={`flex-1 flex items-center justify-center gap-2 py-1.5 text-[10px] font-bold rounded-md transition-all ${activeLibraryTab === 'all' ? 'bg-white/10 text-foreground shadow-sm' : 'text-muted-foreground hover:text-muted-foreground'}`}
                                >
                                    <Folder size={12} /> 所有素材
                                </button>
                            </div>
                        )}

                        {/* Type Tabs: Only show if "all" tab is active (or if sourceContext is null) */}
                        {activeLibraryTab === 'all' && (
                            <div className="flex bg-black/20 p-1 rounded-lg">
                                {[
                                    { id: 'character', label: '角色' },
                                    { id: 'scene', label: '场景' },
                                    { id: 'prop', label: '道具' },
                                    { id: 'other', label: '其他' },
                                ].map(tab => (
                                    <button
                                        key={tab.id}
                                        onClick={() => setActiveLibraryType(tab.id as any)}
                                        className={cn(
                                            "flex-1 py-1 text-[10px] font-bold rounded-md transition-all",
                                            activeLibraryType === tab.id 
                                                ? "bg-white/10 text-foreground shadow-sm" 
                                                : "text-muted-foreground hover:text-muted-foreground hover:bg-white/5"
                                        )}
                                    >
                                        {tab.label}
                                    </button>
                                ))}
                            </div>
                        )}
                    </>
                )}
            </div>
            
            <div className="flex-1 overflow-y-auto p-2 custom-scrollbar space-y-2 relative">
                {viewedAsset ? (
                    // Detail View Grid
                    <div className="grid grid-cols-2 gap-2 p-1 animate-in fade-in slide-in-from-right-4 duration-300">
                        {viewedAssetItems.map(renderAssetItem)}
                        {viewedAssetItems.length === 0 && (
                            <div className="col-span-2 flex flex-col items-center justify-center py-10 text-muted-foreground opacity-60">
                                <ImageIcon size={32} className="mb-2 opacity-50" />
                                <span className="text-[10px]">无相关素材</span>
                            </div>
                        )}
                    </div>
                ) : (
                    // Main List View
                    <>
                        {filteredAndSortedItems.length === 0 ? (
                            <EmptyState 
                                icon={searchQuery ? Search : FolderPlus}
                                title={searchQuery ? "未找到相关素材" : "暂无素材"}
                                description={searchQuery ? "换个关键词试试？" : "你可以通过添加节点来生成素材"}
                                className="py-10 opacity-60"
                                textClassName="text-[10px] tracking-widest uppercase"
                            />
                        ) : (
                            <div className="grid grid-cols-2 gap-2 p-1">
                                {filteredAndSortedItems.map((item, idx) => (
                                    <React.Fragment key={idx}>
                                        {renderAssetItem(item)}
                                    </React.Fragment>
                                ))}
                            </div>
                        )}
                    </>
                )}
            </div>
            
            {/* Large Preview Overlay - Portal to Body to escape overflow/transforms */}
            {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
            )}
        </>
    );
};
