import { useState, useEffect, useCallback } from 'react';
import { useApiRequest } from '../useApi';
import { useWorkflowSelection } from '../../contexts/WorkflowSelectionContext';
import { fetchWorkflows as fetchWorkflowsApi, type Workflow } from '../../api/workflowApi';

export function useWorkflows() {
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [isRefetching, setIsRefetching] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { request } = useApiRequest<null, Workflow[]>();
  const { selectedWorkflowId, clearWorkflow } = useWorkflowSelection();

  const fetchWorkflows = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('🔄 useWorkflows: Fetching workflows from API...');
      const workflowList = await fetchWorkflowsApi(request);
      console.log('✅ useWorkflows: Fetched workflows:', workflowList);
      
      if (Array.isArray(workflowList)) {
        setWorkflows(workflowList);
        console.log(`✅ useWorkflows: Set ${workflowList.length} workflows in state`);
      } else {
        console.warn('⚠️ useWorkflows: API returned non-array data:', workflowList);
        setWorkflows([]);
      }
    } catch (error: any) {
      console.error('❌ useWorkflows: Error fetching workflows:', error);
      setError(error.message || 'Failed to fetch workflows');
      setWorkflows([]);
    } finally {
      setLoading(false);
    }
  }, [request]);

  useEffect(() => {
    fetchWorkflows();
  }, [fetchWorkflows]);

  useEffect(() => {
    const handleWorkflowDeleted = (event: CustomEvent<{ workflowIds: string[] }>) => {
      const deletedIds = event.detail.workflowIds;
      fetchWorkflows();
      if (selectedWorkflowId && deletedIds.includes(selectedWorkflowId)) {
        clearWorkflow();
      }
    };

    const handleWorkflowCreated = () => {
      // Immediately refetch workflows list to include the newly created workflow
      fetchWorkflows();
    };

    window.addEventListener('workflowDeleted', handleWorkflowDeleted as EventListener);
    window.addEventListener('workflowCreated', handleWorkflowCreated as EventListener);
    return () => {
      window.removeEventListener('workflowDeleted', handleWorkflowDeleted as EventListener);
      window.removeEventListener('workflowCreated', handleWorkflowCreated as EventListener);
    };
  }, [fetchWorkflows, selectedWorkflowId, clearWorkflow]);

  const refetch = useCallback(async () => {
    setIsRefetching(true);
    try {
      await fetchWorkflows();
    } finally {
      setIsRefetching(false);
    }
  }, [fetchWorkflows]);

  return { 
    workflows, 
    loading, 
    isRefetching,
    error, 
    refetch 
  };
}

