import { useCallback, useState } from "react";

export type RunAction = (
  message: string,
  task: () => Promise<void>,
) => Promise<void>;

export function useActionFeedback() {
  const [busy, setBusy] = useState(false);
  const [status, setStatus] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const runAction = useCallback<RunAction>(async (message, task) => {
    setBusy(true);
    setError(null);
    setStatus(null);
    try {
      await task();
      setStatus(message);
    } catch (taskError) {
      setError(taskError instanceof Error ? taskError.message : "Request failed");
    } finally {
      setBusy(false);
    }
  }, []);

  return {
    busy,
    status,
    error,
    runAction,
  };
}
