'use client';

import React, { useState, useEffect, useRef } from 'react';
import { 
    Plus, RotateCcw, History, 
    Box, Layers,
    Trash2, Pencil, Clapperboard
} from 'lucide-react';
import { AppNodeData, NodeType } from '../../types/node';
import { Asset, Storyboard, Episode } from '@/types';
import { cn } from '@/utils';
import { useHoverPanel } from '../../hooks/useHoverPanel';

// Sub-components
import { LibraryPanel } from './left/LibraryPanel';
import { StoryboardPanel } from './left/StoryboardPanel';
import { HistoryPanel } from './left/HistoryPanel';
import { AddNodePanel } from './left/AddNodePanel';

interface SidebarDockProps {
    onAddNode: (type: NodeType, data?: Partial<AppNodeData>) => void;
    onUndo: () => void;
    
    // History Props
    assetHistory: any[];
    projectAssets?: Asset[];
    projectStoryboards?: Storyboard[];
    projectEpisodes?: Episode[];
    sourceContext?: { id: string, type: 'asset' | 'storyboard' } | null;
    onHistoryItemClick: (item: any) => void;
    onDeleteAsset: (id: string) => void;
    onDeleteProjectAsset?: (id: string) => void;
    onRenameAsset?: (id: string, newName: string) => void;
    onAddToLibrary?: (item: any) => void;
    
    onOpenProjectDetails: () => void;
    
    // Clear
    onClear: () => void;
}

export const Sidebar = ({
    onAddNode,
    onUndo,
    assetHistory,
    onHistoryItemClick,
    onDeleteAsset,
    onDeleteProjectAsset,
    onRenameAsset,
    onAddToLibrary,
    projectAssets,
    projectStoryboards,
    projectEpisodes,
    sourceContext,
    onOpenProjectDetails,
}: SidebarDockProps) => {
    const { 
        activePanel, 
        setActivePanel, 
        togglePanel,
        closeImmediately
    } = useHoverPanel<'history' | 'workflow' | 'add' | 'library' | 'storyboard'>();

    const [contextMenu, setContextMenu] = useState<{ visible: boolean, x: number, y: number, id: string, type: 'workflow' | 'history' | 'library' } | null>(null);

    // Track last active panel to prevent content flashing during close animation
    const lastActivePanelRef = useRef<string | null>(null);
    useEffect(() => {
        if (activePanel) {
            lastActivePanelRef.current = activePanel;
        }
    }, [activePanel]);

    // Close context menu on global click
    useEffect(() => {
        const handleClick = (e: MouseEvent) => {
            setContextMenu(null);
            
            // Auto close sidebar if clicking outside (optional, but good UX for click-based)
            const target = e.target as HTMLElement;
            if (!target.closest('.sidebar-dock') && !target.closest('.sidebar-panel')) {
                 closeImmediately();
            }
        };
        window.addEventListener('click', handleClick);
        return () => window.removeEventListener('click', handleClick);
    }, [closeImmediately]);

    const renderPanelContent = () => {
        const targetPanel = activePanel || lastActivePanelRef.current;

        if (targetPanel === 'library') {
            return (
                <LibraryPanel 
                    projectAssets={projectAssets} 
                    projectStoryboards={projectStoryboards}
                    onAddToCanvas={onAddToLibrary || (() => {})}
                    onHistoryItemClick={onHistoryItemClick}
                    onContextMenu={(e, item) => {
                        e.preventDefault();
                        setContextMenu({
                            visible: true,
                            x: e.clientX,
                            y: e.clientY,
                            id: item.id,
                            type: 'library'
                        });
                    }}
                    onClose={() => setActivePanel(null)}
                />
            );
        }

        if (targetPanel === 'storyboard') {
            return (
                <StoryboardPanel 
                    projectStoryboards={projectStoryboards}
                    projectEpisodes={projectEpisodes}
                    onAddToCanvas={onAddToLibrary || (() => {})}
                    onHistoryItemClick={onHistoryItemClick}
                    onClose={() => setActivePanel(null)}
                />
            );
        }

        if (targetPanel === 'history') {
            return (
                <HistoryPanel 
                    history={assetHistory} 
                    onRestore={onHistoryItemClick} 
                    onDelete={(id) => {
                        // Handle history deletion if needed
                    }}
                    onClose={() => setActivePanel(null)}
                />
            );
        }

        // Only render AddNodePanel if explicitly 'add'
        if (targetPanel === 'add') {
            return <AddNodePanel onAddNode={onAddNode} onClose={() => setActivePanel(null)} />;
        }

        return null;
    };

    return (
        <>
            {/* Left Vertical Dock */}
            <div 
                className={`fixed left-4 top-1/2 -translate-y-1/2 flex flex-col items-center gap-3 p-1.5 bg-muted/70 backdrop-blur-2xl border border-white/10 rounded-full shadow-2xl z-50 animate-in slide-in-from-left-10 duration-500 ease-spring sidebar-dock`}
            >
                {/* Add Node (Main Action) */}
                <div className="relative group flex items-center justify-center">
                    <button 
                        onClick={() => togglePanel('add')}
                        data-testid="canvas-add-node-toggle"
                        className={cn(
                            "w-10 h-10 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110 active:scale-95 shadow-lg",
                            activePanel === 'add' ? "bg-white text-black rotate-45" : "bg-gradient-to-tr from-brand-from to-brand-to text-white"
                        )}
                    >
                        <Plus size={20} strokeWidth={2.5} />
                    </button>
                    {/* Tooltip */}
                    <div className="absolute left-full ml-3 top-1/2 -translate-y-1/2 px-2 py-1 bg-black/90 backdrop-blur-md rounded-md border border-white/10 text-[10px] text-white font-medium whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50 shadow-xl">
                        添加节点
                    </div>
                </div>

                {[
                    { id: 'library', icon: Box, tooltip: '素材库' },
                    { id: 'storyboard', icon: Clapperboard, tooltip: '分镜库' },
                    { id: 'history', icon: History, tooltip: '历史记录' },
                ].map(item => (
                    <div key={item.id} className="relative group flex items-center justify-center">
                        <button 
                            onClick={() => togglePanel(item.id as any)}
                            className={cn(
                                "relative group w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110 active:scale-95",
                                activePanel === item.id ? 'bg-white text-black shadow-lg' : 'hover:bg-white/10 text-muted-foreground hover:text-black'
                            )}
                        >
                            <item.icon size={16} strokeWidth={2} />
                        </button>
                        <div className="absolute left-full ml-3 top-1/2 -translate-y-1/2 px-2 py-1 bg-black/90 backdrop-blur-md rounded-md border border-white/10 text-[10px] text-white font-medium whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50 shadow-xl">
                            {item.tooltip}
                        </div>
                    </div>
                ))}

                {/* Undo */}
                <div className="relative group">
                    <button 
                        onClick={onUndo}
                        className="w-8 h-8 rounded-full flex items-center justify-center hover:bg-white/10 text-muted-foreground hover:text-white transition-all duration-300 active:scale-95 active:-rotate-45"
                    >
                        <RotateCcw size={16} strokeWidth={2} />
                    </button>
                    <div className="absolute left-full ml-4 top-1/2 -translate-y-1/2 px-2 py-1 bg-black/80 backdrop-blur-md rounded border border-white/10 text-[10px] text-white whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50">
                        撤销
                    </div>
                </div>
                
                {/* Project Details */}
                <div className="relative group">
                    <button 
                        onClick={onOpenProjectDetails}
                        className="w-10 h-10 rounded-full flex items-center justify-center hover:bg-white/10 text-muted-foreground hover:text-white transition-all duration-300 active:scale-95"
                    >
                        <Layers size={18} strokeWidth={2} />
                    </button>
                    <div className="absolute left-full ml-4 top-1/2 -translate-y-1/2 px-2 py-1 bg-black/80 backdrop-blur-md rounded border border-white/10 text-[10px] text-white whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50">
                        项目详情
                    </div>
                </div>
            </div>

            {/* Slide-out Panel */}
            <div 
                className={cn(
                    `fixed left-24 top-1/2 -translate-y-1/2 h-[70vh] w-80 bg-card/85 backdrop-blur-3xl border border-white/10 rounded-2xl shadow-2xl transition-all duration-500 ease-spring z-40 flex flex-col overflow-hidden sidebar-panel`,
                    activePanel ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-10 pointer-events-none"
                )}
                onMouseDown={(e) => e.stopPropagation()}
                onWheel={(e) => e.stopPropagation()}
                onClick={(e) => e.stopPropagation()}
            >
                {renderPanelContent()}
            </div>

            {/* Context Menu */}
            {contextMenu && contextMenu.visible && (
                <div 
                    className="fixed z-[10000] w-32 bg-black/80 backdrop-blur-xl border border-white/10 rounded-lg shadow-2xl overflow-hidden py-1 animate-in fade-in zoom-in-95 duration-200"
                    style={{ left: contextMenu.x, top: contextMenu.y }}
                >
                    {contextMenu.type === 'history' && (
                        <button 
                            className="w-full text-left px-3 py-1.5 text-xs text-red-400 hover:bg-white/10 flex items-center gap-2 transition-colors"
                            onClick={(e) => {
                                e.stopPropagation();
                                onDeleteAsset(contextMenu.id);
                                setContextMenu(null);
                            }}
                        >
                            <Trash2 size={12} />
                            删除记录
                        </button>
                    )}
                    {contextMenu.type === 'library' && (() => {
                        // Resolve ID for sub-items (e.g. in Detail View)
                        let targetId = contextMenu.id;
                        let asset = projectAssets?.find(a => a.id === targetId);
                        
                        if (!asset && projectAssets) {
                            // Try resolving derived ID from LibraryPanel suffixes (-main, -img-N, -vid-N)
                            const match = targetId.match(/(.*)-(?:main|img-\d+|vid-\d+)$/);
                            if (match) {
                                targetId = match[1];
                                asset = projectAssets.find(a => a.id === targetId);
                            }
                        }

                        return (
                            <>
                                <button 
                                    className="w-full text-left px-3 py-1.5 text-xs text-white hover:bg-white/10 flex items-center gap-2 transition-colors"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        if (asset) {
                                            const newName = window.prompt("重命名素材", asset.name);
                                            if (newName && newName.trim() !== "") {
                                                onRenameAsset?.(targetId, newName.trim());
                                            }
                                        }
                                        setContextMenu(null);
                                    }}
                                >
                                    <Pencil size={12} />
                                    重命名
                                </button>
                                <button 
                                    className="w-full text-left px-3 py-1.5 text-xs text-red-400 hover:bg-white/10 flex items-center gap-2 transition-colors"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onDeleteProjectAsset?.(targetId);
                                        setContextMenu(null);
                                    }}
                                >
                                    <Trash2 size={12} />
                                    删除素材
                                </button>
                            </>
                        );
                    })()}
                </div>
            )}
        </>
    );
};
