'use client';

import React, { useState, useRef, useCallback, useEffect, memo } from 'react';
import { Music, UserCircle } from 'lucide-react';
import { SecureVideo } from './SecureVideo';
import { SecureImage } from '@/components/common/SecureImage';
import { InputAsset } from '../../types/node';
import { cn } from '@/utils';

interface InputThumbnailsProps {
    assets: InputAsset[];
    onReorder: (newOrder: string[]) => void;
}

export const InputThumbnails = memo(({ assets, onReorder }: InputThumbnailsProps) => {
    const [draggingId, setDraggingId] = useState<string | null>(null);
    const [dragOffset, setDragOffset] = useState(0);
    const onReorderRef = useRef(onReorder);
    onReorderRef.current = onReorder; 
    const stateRef = useRef({ draggingId: null as string | null, startX: 0, originalAssets: [] as InputAsset[] });
    const THUMB_WIDTH = 40; 
    const GAP = 8;
    const ITEM_FULL_WIDTH = THUMB_WIDTH + GAP;

    const handleGlobalMouseMove = useCallback((e: MouseEvent) => {
        if (!stateRef.current.draggingId) return;
        const delta = e.clientX - stateRef.current.startX;
        setDragOffset(delta);
    }, []);

    const handleGlobalMouseUp = useCallback((e: MouseEvent) => {
        if (!stateRef.current.draggingId) return;
        const { draggingId, startX, originalAssets } = stateRef.current;
        const currentOffset = e.clientX - startX;
        const moveSlots = Math.round(currentOffset / ITEM_FULL_WIDTH);
        const currentIndex = originalAssets.findIndex(a => a.id === draggingId);
        const newIndex = Math.max(0, Math.min(originalAssets.length - 1, currentIndex + moveSlots));

        if (newIndex !== currentIndex) {
            const newOrderIds = originalAssets.map(a => a.id);
            const [moved] = newOrderIds.splice(currentIndex, 1);
            newOrderIds.splice(newIndex, 0, moved);
            onReorderRef.current(newOrderIds);
        }
        setDraggingId(null);
        setDragOffset(0);
        stateRef.current.draggingId = null;
        document.body.style.cursor = '';
        window.removeEventListener('mousemove', handleGlobalMouseMove);
        window.removeEventListener('mouseup', handleGlobalMouseUp);
    }, [ITEM_FULL_WIDTH, handleGlobalMouseMove]); 
    
    useEffect(() => {
        return () => {
            document.body.style.cursor = '';
            window.removeEventListener('mousemove', handleGlobalMouseMove);
            window.removeEventListener('mouseup', handleGlobalMouseUp);
        }
    }, [handleGlobalMouseMove, handleGlobalMouseUp]);

    const handleMouseDown = (e: React.MouseEvent, id: string) => {
        e.stopPropagation();
        e.preventDefault();
        setDraggingId(id);
        setDragOffset(0);
        stateRef.current = { draggingId: id, startX: e.clientX, originalAssets: [...assets] };
        document.body.style.cursor = 'grabbing';
        window.addEventListener('mousemove', handleGlobalMouseMove);
        window.addEventListener('mouseup', handleGlobalMouseUp);
    };

    if (!assets || assets.length === 0) return null;

    return (
        <div className="flex items-center justify-center h-14 pointer-events-none select-none relative z-0" onMouseDown={e => e.stopPropagation()}>
            <div className="relative flex items-center gap-[6px]">
                {assets.map((asset, index) => {
                    const isItemDragging = asset.id === draggingId;
                    const originalIndex = assets.findIndex(a => a.id === draggingId);
                    let translateX = 0;
                    let scale = 1;
                    let zIndex = 10;
                    
                    if (isItemDragging) {
                        translateX = dragOffset;
                        scale = 1.15;
                        zIndex = 100;
                    } else if (draggingId) {
                        const draggingVirtualIndex = Math.max(0, Math.min(assets.length - 1, originalIndex + Math.round(dragOffset / ITEM_FULL_WIDTH)));
                        if (index > originalIndex && index <= draggingVirtualIndex) translateX = -ITEM_FULL_WIDTH;
                        else if (index < originalIndex && index >= draggingVirtualIndex) translateX = ITEM_FULL_WIDTH;
                    }
                    const isVideo = asset.type === 'video';
                    const isAudio = asset.type === 'audio';
                    return (
                        <div 
                            key={asset.id}
                            className={cn(
                                "relative rounded-full overflow-hidden cursor-grab active:cursor-grabbing pointer-events-auto border-2 border-cyan-500/50 shadow-[0_0_10px_rgba(6,182,212,0.3)] bg-black/60 group transition-all duration-200",
                                isItemDragging ? "z-50 scale-110 border-cyan-400" : "z-10 hover:scale-110 hover:border-cyan-400 hover:z-30"
                            )}
                            style={{
                                width: `${THUMB_WIDTH}px`, height: `${THUMB_WIDTH}px`, 
                                transform: `translateX(${translateX}px) scale(${scale})`,
                                zIndex,
                                transition: isItemDragging ? 'none' : 'transform 0.5s cubic-bezier(0.32,0.72,0,1)', 
                            }}
                            onMouseDown={(e) => handleMouseDown(e, asset.id)}
                            title={asset.label || undefined}
                        >
                            {isVideo ? (
                                <SecureVideo src={asset.src} className="w-full h-full object-cover pointer-events-none select-none" muted loop autoPlay />
                            ) : isAudio ? (
                                <div className={cn(
                                    "w-full h-full flex items-center justify-center pointer-events-none select-none",
                                    asset.gender ? "bg-black/40" : "bg-cyan-500/20"
                                )}>
                                    {asset.gender ? (
                                        <UserCircle
                                            size={20}
                                            className={cn(
                                                asset.gender === '男' || asset.gender === 'male' ? 'text-blue-400' : 'text-pink-400'
                                            )}
                                        />
                                    ) : (
                                        <Music className="w-5 h-5 text-cyan-400" />
                                    )}
                                </div>
                            ) : (
                                <SecureImage src={asset.src} className="w-full h-full object-cover pointer-events-none select-none" alt="" />
                            )}
                        </div>
                    )
                })}
            </div>
        </div>
    )
});

InputThumbnails.displayName = 'InputThumbnails';
