import { useState, useCallback } from 'react';
import { Integration } from '../types/integration';
import { TriggerAction } from './useCategorizedItems';

interface UseConnectionManagerProps {
  integrations: Integration[];
  refetchActions: () => Promise<void>;
  refetchIntegrations: () => Promise<void>;
}

interface UseConnectionManagerReturn {
  connectionDialogOpen: boolean;
  connectionDialogIntegration: Integration | null;
  handleNotConnectedClick: (item: TriggerAction) => void;
  handleConnectionsChange: () => Promise<void>;
  setConnectionDialogOpen: (open: boolean) => void;
}

/**
 * Hook for managing the connection manager dialog state.
 * Handles opening the dialog for items that need connection and refreshing data after connection changes.
 */
export function useConnectionManager({
  integrations,
  refetchActions,
  refetchIntegrations,
}: UseConnectionManagerProps): UseConnectionManagerReturn {
  const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
  const [connectionDialogIntegration, setConnectionDialogIntegration] =
    useState<Integration | null>(null);

  // Handle clicking on a not-connected action - open the connection dialog
  const handleNotConnectedClick = useCallback(
    (item: TriggerAction) => {
      const integration = integrations.find((i) => i.slug === item.integration);
      if (integration) {
        setConnectionDialogIntegration(integration);
        setConnectionDialogOpen(true);
      }
    },
    [integrations],
  );

  // Handle connection changes - refresh actions and integrations
  const handleConnectionsChange = useCallback(async () => {
    await Promise.all([refetchActions(), refetchIntegrations()]);
  }, [refetchActions, refetchIntegrations]);

  return {
    connectionDialogOpen,
    connectionDialogIntegration,
    handleNotConnectedClick,
    handleConnectionsChange,
    setConnectionDialogOpen,
  };
}
