import { useState, useCallback } from 'react';

export interface UseAsyncActionReturn<T> {
  execute: (fn: () => Promise<T>) => Promise<T | null>;
  isLoading: boolean;
  error: string | null;
  clearError: () => void;
}

/**
 * DEBT-006: Manages loading/error/success state for async API calls.
 *
 * Replaces the repeated pattern:
 *   const [loading, setLoading] = useState(false);
 *   const [error, setError] = useState<string | null>(null);
 *   try { setLoading(true); await fn(); } catch { setError(...) } finally { setLoading(false); }
 *
 * Usage:
 *   const { execute, isLoading, error } = useAsyncAction<void>();
 *   const handleDelete = () => execute(() => fetch('/api/delete').then(r => r.json()));
 */
export function useAsyncAction<T = void>(): UseAsyncActionReturn<T> {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const clearError = useCallback(() => setError(null), []);

  const execute = useCallback(async (fn: () => Promise<T>): Promise<T | null> => {
    setIsLoading(true);
    setError(null);

    try {
      const result = await fn();
      return result;
    } catch (err: unknown) {
      const message =
        err instanceof Error ? err.message : 'An unexpected error occurred. Try again.';
      setError(message);
      return null;
    } finally {
      setIsLoading(false);
    }
  }, []);

  return { execute, isLoading, error, clearError };
}
