import { useEffect } from 'react';
import { router } from '@inertiajs/react';
import { toast } from 'sonner';

/**
 * Listens for Inertia flash messages (success / error / info / warning / status) and shows a toast.
 * Also displays validation errors as error toasts.
 * Safe to mount anywhere at the root of the app.
 */
export default function FlashToast() {
    useEffect(() => {
        const handlePageProps = (props: any) => {
            if (!props) return;
            const { flash, errors } = props;

            if (flash) {
                if (flash.success) {
                    toast.success(flash.success);
                }
                if (flash.error) {
                    toast.error(flash.error);
                }
                if (flash.info) {
                    toast.info(flash.info);
                }
                if (flash.warning) {
                    toast.warning(flash.warning);
                }
                if (flash.status) {
                    toast.success(flash.status);
                }
            }

            if (errors) {
                const msgs = Array.isArray(errors) ? errors : Object.values(errors).flat();
                msgs.forEach((msg) => {
                    if (typeof msg === 'string') {
                        toast.error(msg);
                    }
                });
            }
        };

        // Check initial page props
        if ((router as any).page?.props) {
            handlePageProps((router as any).page.props);
        }

        // Listen for all subsequent page navigation/mutation events
        const unregister = router.on('navigate', (event: any) => {
            const pageProps = event?.detail?.page?.props;
            handlePageProps(pageProps);
        });

        return () => {
            unregister();
        };
    }, []);

    return null;
}

