import { router } from '@inertiajs/react';
import { useEffect, useState } from 'react';

interface InstallPrompt extends Event { prompt(): Promise<void>; userChoice: Promise<{ outcome: string }> }

export default function PwaControls() {
    const [install, setInstall] = useState<InstallPrompt | null>(null);
    const [online, setOnline] = useState(navigator.onLine);
    const [waiting, setWaiting] = useState<ServiceWorker | null>(null);
    const [installed, setInstalled] = useState(window.matchMedia('(display-mode: standalone)').matches);
    const [blocked, setBlocked] = useState(false);
    useEffect(() => {
        const onInstall = (event: Event) => { event.preventDefault(); setInstall(event as InstallPrompt); };
        const onInstalled = () => { setInstalled(true); setInstall(null); };
        const updateNetwork = () => { setOnline(navigator.onLine); if (navigator.onLine) setBlocked(false); };
        window.addEventListener('beforeinstallprompt', onInstall);
        window.addEventListener('appinstalled', onInstalled);
        window.addEventListener('online', updateNetwork);
        window.addEventListener('offline', updateNetwork);
        const remove = router.on('before', event => {
            if (!navigator.onLine && event.detail.visit.method !== 'get') { event.preventDefault(); setBlocked(true); }
        });
        if ('serviceWorker' in navigator && import.meta.env.PROD) {
            navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none' }).then(registration => {
                if (registration.waiting) setWaiting(registration.waiting);
                registration.addEventListener('updatefound', () => {
                    const worker = registration.installing;
                    worker?.addEventListener('statechange', () => { if (worker.state === 'installed' && navigator.serviceWorker.controller) setWaiting(worker); });
                });
            }).catch(() => { /* The online application remains available if installation fails. */ });
        }
        return () => { remove(); window.removeEventListener('beforeinstallprompt', onInstall); window.removeEventListener('appinstalled', onInstalled); window.removeEventListener('online', updateNetwork); window.removeEventListener('offline', updateNetwork); };
    }, []);
    const activate = () => {
        if (!confirm('Enregistrez ou abandonnez vos formulaires en cours. Recharger maintenant la nouvelle version ?')) return;
        navigator.serviceWorker.addEventListener('controllerchange', () => location.reload(), { once: true });
        waiting?.postMessage({ type: 'ACTIVATE_UPDATE' });
    };
    return <div className="pwa-controls" aria-live="polite">
        {!online && <div className="pwa-message pwa-warning">Hors connexion. Consultation à distance et enregistrement suspendus ; aucune opération ne sera envoyée automatiquement.{blocked && <strong> Opération non enregistrée.</strong>}</div>}
        {waiting && <div className="pwa-message">Une nouvelle version est prête. <button onClick={activate}>Mettre à jour</button></div>}
        {install && !installed && <button className="pwa-install" onClick={async () => { await install.prompt(); await install.userChoice; setInstall(null); }}>Installer CréancePro</button>}
    </div>;
}
