"use client";

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

type ToastTone = "info" | "success" | "warning" | "error";

interface ToastState {
  visible: boolean;
  text: string;
  tone: ToastTone;
}

type SetToastFn = (state: ToastState | ((current: ToastState) => ToastState)) => void;

interface UseCheckoutToastOptions {
  /** External setToast function (e.g., from usePaymentRefresh) */
  setToast: SetToastFn;
  /** Duration in ms before toast auto-hides (default: 2200) */
  duration?: number;
}

/**
 * Hook that encapsulates toast timing logic with auto-hide.
 * Wraps an external setToast function and manages timeout cleanup.
 */
export function useCheckoutToast({ setToast, duration = 2200 }: UseCheckoutToastOptions) {
  const timeoutRef = useRef<number | null>(null);

  const clearTimeoutRef = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, []);

  /**
   * Show a toast with auto-hide after duration.
   */
  const showToast = useCallback(
    (text: string, tone: ToastTone) => {
      clearTimeoutRef();
      setToast({ visible: true, text, tone });
      timeoutRef.current = window.setTimeout(() => {
        setToast(current => ({ ...current, visible: false }));
        timeoutRef.current = null;
      }, duration);
    },
    [clearTimeoutRef, setToast, duration]
  );

  /**
   * Immediately hide the toast.
   */
  const hideToast = useCallback(() => {
    clearTimeoutRef();
    setToast(current => ({ ...current, visible: false }));
  }, [clearTimeoutRef, setToast]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      clearTimeoutRef();
    };
  }, [clearTimeoutRef]);

  return {
    showToast,
    hideToast,
  };
}
