import { router } from '@inertiajs/react';
import { useEffect } from 'react';
import { toast } from 'sonner';
import type { FlashToast } from '@/types/ui';

const FLASH_TOAST_KEYS = ['toast', 'toast_email'] as const;

function showToast(data: FlashToast): void {
    switch (data.type) {
        case 'success':
            toast.success(data.message);
            break;
        case 'error':
            toast.error(data.message);
            break;
        case 'warning':
            toast.warning(data.message);
            break;
        default:
            toast.info(data.message);
    }
}

export function useFlashToast(): void {
    useEffect(() => {
        return router.on('flash', (event) => {
            const flash = (event as CustomEvent).detail?.flash as
                | Record<string, FlashToast | undefined>
                | undefined;

            if (!flash) {
                return;
            }

            for (const key of FLASH_TOAST_KEYS) {
                const data = flash[key];

                if (data?.message) {
                    showToast(data);
                }
            }
        });
    }, []);
}
