import { createContext, useContext, useState, useCallback, ReactNode } from 'react';

interface WorkflowSelectionContextType {
  selectedWorkflowId: string | null;
  selectWorkflow: (workflowId: string | null) => void;
  clearWorkflow: () => void; // Clear workflow and connected files
}

const WorkflowSelectionContext = createContext<WorkflowSelectionContextType | undefined>(undefined);

export function WorkflowSelectionProvider({ children }: { children: ReactNode }) {
  const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);

  const selectWorkflow = useCallback((workflowId: string | null) => {
    setSelectedWorkflowId(workflowId);
    // Also dispatch a custom event for components that might not have access to context
    window.dispatchEvent(new CustomEvent('workflowSelected', { detail: { workflowId } }));
  }, []);

  const clearWorkflow = useCallback(() => {
    setSelectedWorkflowId(null);
    // Dispatch event to notify that workflow is cleared - connected files should also be cleared
    window.dispatchEvent(new CustomEvent('workflowCleared', { detail: { workflowId: null } }));
    // Also dispatch workflowSelected with null for backward compatibility
    window.dispatchEvent(new CustomEvent('workflowSelected', { detail: { workflowId: null } }));
  }, []);

  return (
    <WorkflowSelectionContext.Provider value={{ selectedWorkflowId, selectWorkflow, clearWorkflow }}>
      {children}
    </WorkflowSelectionContext.Provider>
  );
}

export function useWorkflowSelection() {
  const context = useContext(WorkflowSelectionContext);
  if (context === undefined) {
    throw new Error('useWorkflowSelection must be used within a WorkflowSelectionProvider');
  }
  return context;
}
