import { toast } from 'sonner';

/**
 * Toast utility for displaying notifications
 * Provides consistent toast messages across the application
 */

export const toastSuccess = (message: string, description?: string) => {
    toast.dismiss();
    return toast.success(message, description ? { description } : undefined);
};

export const toastError = (message: string, description?: string) => {
    toast.dismiss();
    return toast.error(message, description ? { description } : undefined);
};

export const toastInfo = (message: string, description?: string) => {
    return toast.info(message, description ? { description } : undefined);
};

export const toastWarning = (message: string, description?: string) => {
    return toast.warning(message, description ? { description } : undefined);
};

export const toastLoading = (message: string) => {
    return toast.loading(message);
};

export const toastFinishLoading = () => {
    return toast.dismiss();
};

/**
 * Promise toast - automatically handles success/error states
 * @param promise - The promise to track
 * @param messages - Success and error messages
 * @returns Promise that resolves with the result
 */
export const toastPromise = <T>(
    promise: Promise<T>,
    messages: {
        loading: string;
        success: string;
        error: string;
    },
): Promise<T> => {
    return toast.promise(promise, {
        loading: messages.loading,
        success: messages.success,
        error: messages.error,
    });
};

/**
 * Inertia form toast helper
 * Shows loading state during form submission and handles result
 */
export const useFormToast = () => {
    const showSuccess = (message: string) => {
        toast.success(message);
    };

    const showError = (errors: Record<string, string[] | string> | string) => {
        if (typeof errors === 'string') {
            toast.error(errors);
            return;
        }

        const firstError = Object.values(errors)[0];
        const message = Array.isArray(firstError) ? firstError[0] : firstError;
        toast.error(message || 'An error occurred');
    };

    return {
        showSuccess,
        showError,
    };
};

// Re-export everything from sonner for direct access
export { toast };
