import { useEffect } from 'react';
import { AppNodeData, InputAsset } from '../types/node';
import { sortInputAssetsByTypeOrder } from '../utils';
import { useNodeInput } from './useNodeInput';

export const useNodeDataSync = (
    id: string, 
    data: AppNodeData, 
    update: (data: Partial<AppNodeData>) => void
) => {
    const { inputPrompt, inputAssets } = useNodeInput(id);

    useEffect(() => {
        const hasPromptChanged = inputPrompt !== data.inputPrompt;
        
        const currentAssets = data.inputAssets || [];
        const upstreamAssets = inputAssets; // from hook

        // 1. Find assets that are in upstream but not in current (New items)
        const newItems = upstreamAssets.filter(ua => !currentAssets.some(ca => ca.id === ua.id));
        
        // 2. Find assets that are in current but not in upstream (Removed items)
        const removedIds = currentAssets.filter(ca => !upstreamAssets.some(ua => ua.id === ca.id)).map(ca => ca.id);
        
        // 3. Construct new list: Keep current assets (except removed), update their src; 新添加的素材始终插在最前面
        let nextAssets = currentAssets
            .filter(ca => !removedIds.includes(ca.id))
            .map(ca => {
                const ua = upstreamAssets.find(u => u.id === ca.id);
                return ua ? { ...ca, src: ua.src, type: ua.type, gender: ua.gender } : ca;
            });
            
        if (newItems.length > 0) {
            nextAssets = [...newItems, ...nextAssets];
        }
        nextAssets = sortInputAssetsByTypeOrder(nextAssets);

        // Check for changes
        const hasAssetsChanged = 
            nextAssets.length !== currentAssets.length ||
            nextAssets.some((na, i) => na.id !== currentAssets[i].id || na.src !== currentAssets[i].src);

        if (hasPromptChanged || hasAssetsChanged) {
            update({ 
                inputPrompt, 
                inputAssets: nextAssets 
            });
        }
    }, [inputPrompt, inputAssets, data.inputPrompt, data.inputAssets, update]);

    const handleInputReorder = (newOrderIds: string[]) => {
        const currentAssets = data.inputAssets || [];
        const newAssets = newOrderIds.map(id => currentAssets.find(a => a.id === id)).filter(Boolean) as InputAsset[];
        update({ inputAssets: sortInputAssetsByTypeOrder(newAssets) });
    };

    return {
        inputPrompt,
        inputAssets,
        handleInputReorder
    };
};
