import { useState } from 'react';
import { InstallResult } from '../../types';

interface ToolOperationCallbacks {
  onSuccess?: () => void;
  onError?: (error: Error) => void;
  onComplete?: () => void;
}

interface UseToolOperationReturn {
  isRunning: boolean;
  result: InstallResult | null;
  execute: (
    operation: () => Promise<InstallResult>,
    outputListener?: (callback: (output: string) => void) => () => void,
    onOutputReceived?: (output: string) => void,
    callbacks?: ToolOperationCallbacks
  ) => Promise<void>;
  clearResult: () => void;
}

/**
 * Custom hook for managing tool installation/update/reinstall operations.
 * Handles loading states, result management, and output listener lifecycle.
 */
export function useToolOperation(): UseToolOperationReturn {
  const [isRunning, setIsRunning] = useState(false);
  const [result, setResult] = useState<InstallResult | null>(null);

  const execute = async (
    operation: () => Promise<InstallResult>,
    outputListener?: (callback: (output: string) => void) => () => void,
    onOutputReceived?: (output: string) => void,
    callbacks?: ToolOperationCallbacks
  ) => {
    setIsRunning(true);
    setResult(null);

    // Set up output listener if provided
    const cleanup = outputListener && onOutputReceived
      ? outputListener(onOutputReceived)
      : undefined;

    try {
      const operationResult = await operation();
      setResult(operationResult);

      if (operationResult.success) {
        callbacks?.onSuccess?.();
      }
    } catch (error: any) {
      const errorResult: InstallResult = {
        success: false,
        message: error.message || 'Operation failed'
      };
      setResult(errorResult);
      callbacks?.onError?.(error);
    } finally {
      setIsRunning(false);
      cleanup?.();
      callbacks?.onComplete?.();
    }
  };

  const clearResult = () => {
    setResult(null);
  };

  return {
    isRunning,
    result,
    execute,
    clearResult
  };
}
