import React, { useEffect, useState } from 'react';
import { Bell, BellOff, X, Check } from 'lucide-react';
import { toast } from 'sonner';

function getPermission() {
    if (typeof window === 'undefined' || !('Notification' in window)) return 'unsupported';
    return Notification.permission;
}

export default function NotificationBanner() {
    const [perm, setPerm] = useState(getPermission());
    const [dismissed, setDismissed] = useState(() => sessionStorage.getItem('notif_banner_dismissed') === '1');

    useEffect(() => {
        // Re-check permission periodically (user might change it in browser settings)
        const i = setInterval(() => setPerm(getPermission()), 2000);
        return () => clearInterval(i);
    }, []);

    if (perm === 'unsupported' || perm === 'granted' || dismissed) return null;

    const ask = async () => {
        try {
            const result = await Notification.requestPermission();
            setPerm(result);
            if (result === 'granted') {
                toast.success('Notifications activées');
                // Fire a test notification
                try {
                    new Notification('Notifications activées', {
                        body: 'Vous recevrez les alertes même en dehors de cet onglet.',
                        icon: '/logo.png',
                    });
                } catch (_) {}
            } else if (result === 'denied') {
                toast.error('Notifications refusées. Activez-les dans les réglages du navigateur.');
            }
        } catch (e) {
            toast.error('Impossible de demander l\'autorisation');
        }
    };

    const close = () => {
        sessionStorage.setItem('notif_banner_dismissed', '1');
        setDismissed(true);
    };

    const isBlocked = perm === 'denied';

    return (
        <div
            data-testid="notification-banner"
            className={`mb-5 sm:mb-6 rounded-lg border p-4 flex items-start gap-3 ${
                isBlocked ? 'border-red-200 bg-red-50' : 'border-stef/30 bg-stef/5'
            }`}
            style={!isBlocked ? { borderLeftWidth: '4px', borderLeftColor: '#0050E6' } : { borderLeftWidth: '4px', borderLeftColor: '#DC2626' }}
        >
            <div className={`flex h-9 w-9 sm:h-10 sm:w-10 items-center justify-center rounded-md shrink-0 ${
                isBlocked ? 'bg-red-100 text-red-600' : 'bg-stef/10 text-stef'
            }`}>
                {isBlocked ? <BellOff className="h-4 w-4 sm:h-5 sm:w-5" /> : <Bell className="h-4 w-4 sm:h-5 sm:w-5" />}
            </div>
            <div className="flex-1 min-w-0">
                <p className="font-heading font-bold text-sm sm:text-base text-slate-900">
                    {isBlocked ? 'Notifications bloquées' : 'Activez les notifications'}
                </p>
                <p className="mt-0.5 text-xs sm:text-sm text-slate-600">
                    {isBlocked
                        ? 'Activez-les dans les réglages du navigateur (cadenas à gauche de l\'URL → Notifications → Autoriser) pour recevoir les alertes en dehors de cet onglet.'
                        : 'Pour recevoir les alertes son + popup système même quand vous êtes sur un autre onglet, autorisez les notifications.'}
                </p>
            </div>
            {!isBlocked && (
                <button
                    data-testid="enable-notifications-btn"
                    onClick={ask}
                    className="inline-flex items-center gap-2 rounded-md bg-stef px-3 sm:px-4 h-10 text-xs sm:text-sm font-heading font-bold text-white hover:bg-stef-hover transition-all shrink-0"
                >
                    <Check className="h-4 w-4" /> <span className="hidden sm:inline">Activer</span>
                </button>
            )}
            <button
                data-testid="dismiss-notif-banner"
                onClick={close}
                className="h-8 w-8 rounded-md text-slate-400 hover:text-slate-600 hover:bg-slate-100 flex items-center justify-center shrink-0"
                aria-label="Fermer"
            >
                <X className="h-4 w-4" />
            </button>
        </div>
    );
}
