'use client';

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { useReactFlow } from '@xyflow/react';
import { useCanvasStore } from '@/lib/store/canvasStore';
import { useProjectStore } from '@/lib/store/project';
import { CanvasContext, CanvasContextType } from './CanvasContext';
import { useCanvasInitialization } from './managers/useCanvasInitialization';
import { getStorageKey } from './managers/persistenceUtils';
import { saveCanvasStateToStorage } from './services/storage';

interface CanvasManagerProps extends CanvasContextType {
  children: React.ReactNode;
}

export function CanvasManager({ 
  children, 
  initialAssetId, 
  initialStoryboardId, 
  onClose,
  onUpdateAsset,
  onUpdateStoryboard
}: CanvasManagerProps) {
  const projectId = useProjectStore((s) => s.id);
  const setNodes = useCanvasStore((state) => state.setNodes);
  const setEdges = useCanvasStore((state) => state.setEdges);
  const nodes = useCanvasStore((state) => state.nodes);
  const edges = useCanvasStore((state) => state.edges);

  const getStorageKeyWithProject = useCallback(
    (id: string | null, type: string) => getStorageKey(id, type, projectId),
    [projectId]
  );

  const { 
    activeCanvasId, setActiveCanvasId,
    activeCanvasType, setActiveCanvasType,
    isCanvasLoaded, setIsCanvasLoaded,
    currentCanvasMetadata
  } = useCanvasInitialization({
    setNodes,
    setEdges,
    getStorageKey: getStorageKeyWithProject
  });

  const handleSwitchCanvas = useCallback(async (id: string | null, type: 'main' | 'asset' | 'storyboard') => {
    // 1. Save Current
    try {
      const currentKey = getStorageKey(activeCanvasId, activeCanvasType, projectId);
      await saveCanvasStateToStorage(currentKey, { nodes, edges }, projectId || undefined);
    } catch (error) {
      console.error('[Canvas] Failed to save before switch:', error);
    }
    
    // 2. Set New State & Trigger Re-init
    setActiveCanvasId(id);
    setActiveCanvasType(type);
    setIsCanvasLoaded(false);
  }, [activeCanvasId, activeCanvasType, nodes, edges, projectId, setActiveCanvasId, setActiveCanvasType, setIsCanvasLoaded]);

  const contextValue = useMemo(() => ({
    initialAssetId,
    initialStoryboardId,
    onClose,
    onUpdateAsset,
    onUpdateStoryboard,
    activeCanvasId,
    activeCanvasType,
    switchCanvas: handleSwitchCanvas,
    isCanvasLoaded,
    currentCanvasMetadata
  }), [
    initialAssetId, 
    initialStoryboardId, 
    onClose, 
    onUpdateAsset, 
    onUpdateStoryboard, 
    activeCanvasId, 
    activeCanvasType, 
    handleSwitchCanvas, 
    isCanvasLoaded, 
    currentCanvasMetadata
  ]);

  return (
    <CanvasContext.Provider value={contextValue}>
      {children}
    </CanvasContext.Provider>
  );
}
