import { useState, useCallback, useMemo } from 'react';
import { useCanvasStore } from '@lib/store/canvasStore';
import { useProjectStore } from '@lib/store/project';

/**
 * Hook to manage Canvas state and provide common operations
 * Extracts state management logic from Canvas component
 */
export const useCanvasState = () => {
    // Canvas store state
    const nodes = useCanvasStore((state) => state.nodes);
    const onNodesChange = useCanvasStore((state) => state.onNodesChange);
    const setNodes = useCanvasStore((state) => state.setNodes);
    
    const edges = useCanvasStore((state) => state.edges);
    const onEdgesChange = useCanvasStore((state) => state.onEdgesChange);
    const setEdges = useCanvasStore((state) => state.setEdges);
    const onConnect = useCanvasStore((state) => state.onConnect);
    const takeSnapshot = useCanvasStore((state) => state.saveHistory);
    const undo = useCanvasStore((state) => state.undo);
    const redo = useCanvasStore((state) => state.redo);
    
    const isSaving = useCanvasStore((state) => state.isSaving);
    const isDirty = useCanvasStore((state) => state.isDirty);
    const lastSavedAt = useCanvasStore((state) => state.lastSavedAt);
    
    const generationHistory = useCanvasStore((state) => state.generationHistory);
    const setGenerationHistory = useCanvasStore((state) => state.setGenerationHistory);
    
    // Project store state
    const assets = useProjectStore((state) => state.assets);
    const storyboards = useProjectStore((state) => state.storyboards);
    const episodes = useProjectStore((state) => state.episodes);
    const updateAsset = useProjectStore((state) => state.updateAsset);
    const deleteAsset = useProjectStore((state) => state.deleteAsset);
    
    // Memoize sorted storyboards for consistent navigation
    const sortedStoryboards = useMemo(() => {
        const episodeOrderMap = new Map(episodes.map(e => [e.id, e.order]));
        return [...storyboards].sort((a, b) => {
            const orderA = episodeOrderMap.get(a.episodeId) ?? Infinity;
            const orderB = episodeOrderMap.get(b.episodeId) ?? Infinity;
            if (orderA !== orderB) return orderA - orderB;
            return a.order - b.order;
        });
    }, [storyboards, episodes]);
    
    return {
        // Canvas state
        nodes,
        edges,
        onNodesChange,
        onEdgesChange,
        setNodes,
        setEdges,
        onConnect,
        takeSnapshot,
        
        // History
        undo,
        redo,
        
        // Save state
        isSaving,
        isDirty,
        lastSavedAt,
        
        // Generation history
        generationHistory,
        setGenerationHistory,
        
        // Project data
        assets,
        storyboards: sortedStoryboards,
        episodes,
        updateAsset,
        deleteAsset,
    };
};
