'use client';

import React, { useState, useEffect } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { useProjectStore } from '@lib/store/project';
import { cn } from '@/utils';
import { Clapperboard, Folder, LayoutGrid, ChevronLeft, Trash2 } from 'lucide-react';
import { useCanvasContext } from '../../CanvasContext';
import { useHoverPanel } from '../../hooks/useHoverPanel';
import { RightSidebarPanel } from './right/RightSidebarPanel';
import { GeneralCanvas } from '@/types';

type Tab = 'storyboard' | 'asset' | 'general' | null;

export const RightSidebar = ({ 
    activeCanvasId,  
    activeCanvasType, 
    onSwitchCanvas 
}: { 
    activeCanvasId?: string | null, 
    activeCanvasType?: 'main' | 'asset' | 'storyboard',
    onSwitchCanvas?: (id: string | null, type: 'main' | 'asset' | 'storyboard') => void 
}) => {
    const { storyboards, assets, generalCanvases, episodes, addGeneralCanvas, deleteGeneralCanvas, deleteStoryboard, deleteAsset } = useProjectStore(
        useShallow((s) => ({
            storyboards: s.storyboards,
            assets: s.assets,
            generalCanvases: s.generalCanvases,
            episodes: s.episodes,
            addGeneralCanvas: s.addGeneralCanvas,
            deleteGeneralCanvas: s.deleteGeneralCanvas,
            deleteStoryboard: s.deleteStoryboard,
            deleteAsset: s.deleteAsset,
        }))
    );
    const [contextMenu, setContextMenu] = useState<{
        visible: boolean;
        x: number;
        y: number;
        id: string;
        type: 'storyboard' | 'asset' | 'general';
    } | null>(null);

    useEffect(() => {
        const handleClick = () => setContextMenu(null);
        window.addEventListener('click', handleClick);
        return () => window.removeEventListener('click', handleClick);
    }, []);

    const { initialStoryboardId, initialAssetId } = useCanvasContext();
    const [isCollapsed, setIsCollapsed] = useState(true);
    
    const { 
        activePanel: activeTab, 
        setActivePanel: setActiveTab,
        togglePanel,
        closeImmediately
    } = useHoverPanel<'storyboard' | 'asset' | 'general'>();

    // Global Click Handler for closing sidebar and context menu
    useEffect(() => {
        const handleClick = (e: MouseEvent) => {
            setContextMenu(null);
            
             // Auto close sidebar if clicking outside
            const target = e.target as HTMLElement;
            if (!target.closest('.right-sidebar-dock') && !target.closest('.right-sidebar-panel')) {
                 closeImmediately();
            }
        };
        window.addEventListener('click', handleClick);
        return () => window.removeEventListener('click', handleClick);
    }, [closeImmediately]);

    const handleNavigate = (id: string, type: 'storyboard' | 'asset' | 'general') => {
        if (onSwitchCanvas) {
            // map 'general' to 'main' for the parent component if needed, 
            // or update the parent to handle 'general'
            // For now, assume 'main' is used for general canvases
            const targetType = type === 'general' ? 'main' : type;
            onSwitchCanvas(id, targetType);
        }
    };

    const handleCreateGeneralCanvas = () => {
        const newCanvas: GeneralCanvas = {
            id: crypto.randomUUID(),
            name: `画布 ${generalCanvases.length + 1}`,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        addGeneralCanvas(newCanvas);
        handleNavigate(newCanvas.id, 'general');
    };
    
    const activeItemId = activeCanvasId || initialStoryboardId || initialAssetId || null;

    // Hover Handlers
    const handleSidebarHover = (id: Tab) => {
        // Deprecated: Hover is now handled by CSS or unused
    };

    const items = [
        { id: 'general', icon: LayoutGrid, tooltip: '通用画布' },
        { id: 'storyboard', icon: Clapperboard, tooltip: '分镜画布' },
        { id: 'asset', icon: Folder, tooltip: '资产画布' },
    ];

    return (
        <>
            {/* Right Vertical Dock */}
            <div 
                className={cn(
                    `fixed right-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 shadow-2xl z-50 animate-in slide-in-from-right-10 duration-500 ease-spring transition-all right-sidebar-dock`,
                    isCollapsed ? "h-11 w-11 rounded-full justify-center overflow-hidden" : "h-auto rounded-full py-3"
                )}
                onMouseEnter={() => setIsCollapsed(false)}
                onMouseLeave={() => setIsCollapsed(true)}
            >
                {isCollapsed ? (
                    <div className="text-muted-foreground">
                        <ChevronLeft size={16} strokeWidth={2} />
                    </div>
                ) : (
                    items.map(item => (
                        <div key={item.id} className="relative group">
                            <button 
                                onClick={() => togglePanel(item.id as 'storyboard' | 'asset' | 'general')}
                                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",
                                    activeTab === item.id ? 'bg-white text-black shadow-lg' : 'hover:bg-white/10 text-muted-foreground hover:text-black',
                                    activeCanvasType === (item.id === 'general' ? 'main' : item.id) && activeTab !== item.id && "border border-brand-from/50 text-brand-from bg-brand-from/10"
                                )}
                            >
                                <item.icon size={16} strokeWidth={2} />
                            </button>
                            {/* Tooltip */}
                            <div className="absolute right-full mr-3 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">
                                {item.tooltip}
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* Slide-out Panel */}
            <div 
                className={cn(
                    `fixed right-24 top-1/2 -translate-y-1/2 max-h-[75vh] h-auto w-72 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 right-sidebar-panel`,
                    activeTab ? "translate-x-0 opacity-100" : "translate-x-10 opacity-0 pointer-events-none scale-95"
                )}
                onMouseDown={(e) => e.stopPropagation()}
                onWheel={(e) => e.stopPropagation()}
            >
                <RightSidebarPanel 
                    activeTab={activeTab}
                    onClose={() => setActiveTab(null)}
                    storyboards={storyboards}
                    episodes={episodes}
                    assets={assets}
                    generalCanvases={generalCanvases}
                    activeItemId={activeItemId}
                    onNavigate={handleNavigate}
                    onCreateGeneralCanvas={handleCreateGeneralCanvas}
                    onContextMenu={(e, item, type) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setContextMenu({
                            visible: true,
                            x: e.clientX,
                            y: e.clientY,
                            id: item.id,
                            type: type
                        });
                    }}
                />
            </div>

            {/* Context Menu */}
            {contextMenu && contextMenu.visible && (
                <div 
                    className="fixed z-[100] 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 }}
                >
                    <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();
                            if (contextMenu.type === 'general') {
                                deleteGeneralCanvas(contextMenu.id);
                            } else if (contextMenu.type === 'storyboard') {
                                deleteStoryboard(contextMenu.id);
                            } else if (contextMenu.type === 'asset') {
                                deleteAsset(contextMenu.id);
                            }
                            setContextMenu(null);
                        }}
                    >
                        <Trash2 size={12} />
                        删除{contextMenu.type === 'general' ? '画布' : contextMenu.type === 'storyboard' ? '分镜' : '资产'}
                    </button>
                </div>
            )}
        </>
    );
};
