import { useCallback, useEffect, useRef, useState } from "react";

export default function useCooldownAction({
  cooldownMs = 3000,
  toastGapMs = 900,
  isBusy = false,
  busyMessage = "در حال انجام...",
  busyToast, // (msg, opts) => void  (معمولاً info)
  title = "",
  onRun, // async () => {}
}) {
  const inFlightRef = useRef(false);
  const lastAtRef = useRef(0);
  const toastLockRef = useRef(0);
  const [leftMs, setLeftMs] = useState(0);

  useEffect(() => {
    if (leftMs <= 0) return;
    const t = setInterval(() => {
      const left = Math.max(0, cooldownMs - (Date.now() - lastAtRef.current));
      setLeftMs(left);
      if (left <= 0) clearInterval(t);
    }, 120);
    return () => clearInterval(t);
  }, [leftMs, cooldownMs]);

  const run = useCallback(async () => {
    const now = Date.now();

    if (inFlightRef.current || isBusy) {
      if (busyToast && now - toastLockRef.current > toastGapMs) {
        toastLockRef.current = now;
        busyToast(busyMessage, title ? { title } : undefined);
      }
      return;
    }

    const diff = now - lastAtRef.current;
    if (diff < cooldownMs) {
      const left = cooldownMs - diff;
      setLeftMs(left);
      if (busyToast && now - toastLockRef.current > toastGapMs) {
        toastLockRef.current = now;
        busyToast(`لطفاً ${Math.ceil(left / 1000)} ثانیه صبر کن.`, title ? { title } : undefined);
      }
      return;
    }

    inFlightRef.current = true;
    lastAtRef.current = now;
    setLeftMs(cooldownMs);

    try {
      await onRun?.();
    } finally {
      inFlightRef.current = false;
    }
  }, [busyMessage, busyToast, cooldownMs, isBusy, onRun, title, toastGapMs]);

  const disabled = isBusy || leftMs > 0 || inFlightRef.current;

  return { run, disabled, leftMs, inFlightRef };
}
