import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

type ToastVariant = 'success' | 'error' | 'info' | 'warning';

interface NotifyOptions {
  descriptionKey?: string;
  values?: Record<string, string | number>;
  duration?: number;
}

export function useNotify() {
  const { t } = useTranslation();

  function notify(variant: ToastVariant, messageKey: string, options?: NotifyOptions) {
    const message = t(messageKey, options?.values);
    const description = options?.descriptionKey
      ? t(options.descriptionKey, options?.values)
      : undefined;
    const duration = options?.duration;

    switch (variant) {
      case 'success': toast.success(message, { description, duration: duration ?? 3000 }); break;
      case 'error':   toast.error(message, { description, duration: duration ?? Infinity }); break;
      case 'info':    toast.info(message, { description, duration: duration ?? 3000 }); break;
      case 'warning': toast.warning(message, { description, duration: duration ?? 4000 }); break;
    }
  }

  function notifyError(messageKey: string, error?: { message?: string }) {
    toast.error(t(messageKey), { description: error?.message, duration: Infinity });
  }

  function notifyPromise<T>(promise: Promise<T>, keys: { loading: string; success: string; error: string }) {
    toast.promise(promise, { loading: t(keys.loading), success: t(keys.success), error: t(keys.error) });
  }

  return { notify, notifyError, notifyPromise };
}
