import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, usePage, router } from '@inertiajs/react';
import { AlertCircle, Bell, CheckCircle, Info, XCircle, ChevronRight, Clock, User, Package, MessageSquare, AlertTriangle, X, Boxes, MailOpen, Filter, CheckCheck } from 'lucide-react';
import { playNotificationAlertSound } from '@/lib/notification-sound';
import { Breadcrumbs } from '@/components/breadcrumbs';
import { SidebarTrigger } from '@/components/ui/sidebar';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import type { BreadcrumbItem as BreadcrumbItemType } from '@/types';
import type { SharedData } from '@/types';

type PendingRequest = {
    id: number;
    from_partner_name: string;
    type: string;
    type_label: string;
    created_at: string;
};

type NotificationAlert = 'success' | 'warning' | 'destructive' | 'info';

type UserNotification = {
    id: string;
    type: string;
    message: string;
    alert?: NotificationAlert;
    read_at: string | null;
    created_at: string;
    order_id?: number | null;
    order_reference?: string | null;
    data?: Record<string, any>;
};

// Configuration des alertes avec couleurs rouge/bleu/vert/noir
const alertConfig: Record<
    NotificationAlert,
    { 
        label: string; 
        icon: typeof Info; 
        borderClass: string; 
        bgClass: string;
        textClass: string;
        iconBgClass: string;
        iconTextClass: string;
        badgeVariant: 'default' | 'secondary' | 'destructive' | 'outline' 
    }
> = {
    success: {
        label: 'Succès',
        icon: CheckCircle,
        borderClass: 'border-l-green-500',
        bgClass: 'bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-950/20 dark:to-emerald-950/20',
        textClass: 'text-green-700 dark:text-green-300',
        iconBgClass: 'bg-gradient-to-r from-green-100 to-green-200 dark:from-green-900/40 dark:to-emerald-900/40',
        iconTextClass: 'text-green-600 dark:text-green-400',
        badgeVariant: 'default',
    },
    warning: {
        label: 'Attention',
        icon: AlertCircle,
        borderClass: 'border-l-amber-500',
        bgClass: 'bg-gradient-to-r from-amber-50 to-yellow-50 dark:from-amber-950/20 dark:to-yellow-950/20',
        textClass: 'text-amber-700 dark:text-amber-300',
        iconBgClass: 'bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900/40 dark:to-yellow-900/40',
        iconTextClass: 'text-amber-600 dark:text-amber-400',
        badgeVariant: 'outline',
    },
    destructive: {
        label: 'Urgent',
        icon: XCircle,
        borderClass: 'border-l-red-500',
        bgClass: 'bg-gradient-to-r from-red-50 to-rose-50 dark:from-red-950/20 dark:to-rose-950/20',
        textClass: 'text-red-700 dark:text-red-300',
        iconBgClass: 'bg-gradient-to-r from-red-100 to-rose-100 dark:from-red-900/40 dark:to-rose-900/40',
        iconTextClass: 'text-red-600 dark:text-red-400',
        badgeVariant: 'destructive',
    },
    info: {
        label: 'Information',
        icon: Info,
        borderClass: 'border-l-blue-500',
        bgClass: 'bg-gradient-to-r from-blue-50 to-cyan-50 dark:from-blue-950/20 dark:to-cyan-950/20',
        textClass: 'text-blue-700 dark:text-blue-300',
        iconBgClass: 'bg-gradient-to-r from-blue-100 to-cyan-100 dark:from-blue-900/40 dark:to-cyan-900/40',
        iconTextClass: 'text-blue-600 dark:text-blue-400',
        badgeVariant: 'secondary',
    },
};

export function AppSidebarHeader({
    breadcrumbs = [],
}: {
    breadcrumbs?: BreadcrumbItemType[];
}) {
    const {
        auth,
        alerts = {},
        pendingCollaborationRequests = [],
        userNotifications = [],
        permissions,
    } = (usePage<SharedData>().props) as {
        auth?: { user?: { role?: string; name?: string } };
        alerts?: { stockAlerts?: number };
        pendingCollaborationRequests?: PendingRequest[];
        userNotifications?: UserNotification[];
        permissions?: { notifications?: { can_view?: boolean; can_edit?: boolean } };
    };
    
    const canViewNotifications = Boolean(permissions?.notifications?.can_view);
    const isDriver = auth?.user?.role === 'livreur';
    const userName = auth?.user?.name || 'Utilisateur';
    
    // Gestion des notifications non lues
    const partnerUnreadNotifications = userNotifications.filter((n) => !n.read_at).length;
    const unreadCount = isDriver
        ? partnerUnreadNotifications
        : partnerUnreadNotifications + pendingCollaborationRequests.length;
    
    const showBell = canViewNotifications;
    const stockAlertsCount = alerts?.stockAlerts ?? 0;
    const showStockAlert = !isDriver && stockAlertsCount > 0;
    const [activeTab, setActiveTab] = useState<'all' | 'unread'>('all');
    const [isOpen, setIsOpen] = useState(false);

    const notificationStorageKey = `e_logi_unread_count_${auth?.user?.id ?? 'anon'}`;
    const NOTIFICATION_POLL_INTERVAL_MS = 40_000; // 40 secondes

    // Pas de rechargement tant que le centre est ouvert avec des non lues sur l'onglet "Non lues" (jusqu'à clic "Toutes" ou fermeture)
    const skipReloadRef = useRef(false);
    useEffect(() => {
        skipReloadRef.current = isOpen && partnerUnreadNotifications > 0 && activeTab === 'unread';
    }, [isOpen, partnerUnreadNotifications, activeTab]);

    // Filtrage des notifications selon l'onglet actif
    const filteredNotifications = useMemo(() => {
        if (activeTab === 'unread') {
            return userNotifications.filter(n => !n.read_at);
        }
        return userNotifications;
    }, [userNotifications, activeTab]);

    // Sonnerie pour toutes les nouvelles notifications : prestataire, partenaire et livreur
    useEffect(() => {
        if (!showBell || unreadCount === 0) return;
        const prevRaw = sessionStorage.getItem(notificationStorageKey);
        const prev = prevRaw !== null && prevRaw !== '' ? parseInt(prevRaw, 10) : 0;
        const prevCount = Number.isNaN(prev) ? 0 : prev;
        if (unreadCount > prevCount) {
            playNotificationAlertSound();
        }
        sessionStorage.setItem(notificationStorageKey, String(unreadCount));
    }, [showBell, unreadCount, notificationStorageKey]);

    // Rechargement périodique des notifications (sauf si centre ouvert avec des non lues)
    useEffect(() => {
        if (!showBell || !auth?.user) return;
        const reloadNotifications = () => {
            if (skipReloadRef.current) return;
            router.reload({
                only: ['userNotifications', 'pendingCollaborationRequests', 'alerts'],
                preserveScroll: true,
            });
        };
        const intervalId = setInterval(reloadNotifications, NOTIFICATION_POLL_INTERVAL_MS);
        const handleVisibility = () => {
            if (document.visibilityState === 'visible' && !skipReloadRef.current) {
                reloadNotifications();
            }
        };
        document.addEventListener('visibilitychange', handleVisibility);
        return () => {
            clearInterval(intervalId);
            document.removeEventListener('visibilitychange', handleVisibility);
        };
    }, [showBell, auth?.user]);

    // Marquer toutes les notifications comme lues et réinitialiser le compteur
    const markAllAsRead = () => {
        const doReload = () => {
            sessionStorage.setItem(notificationStorageKey, '0');
            router.reload({
                only: ['userNotifications', 'pendingCollaborationRequests', 'alerts'],
                preserveScroll: true,
            });
        };
        if (isDriver) {
            router.post('/livreur/notifications/marquer-lues', {}, {
                preserveScroll: true,
                onSuccess: doReload,
            });
        } else {
            router.post('/notifications/marquer-lues', {}, {
                preserveScroll: true,
                onSuccess: doReload,
            });
        }
    };

    // Naviguer vers une commande (partenaire / admin)
    const navigateToOrder = (orderId?: number | null) => {
        if (orderId) {
            router.get('/commandes', { order_id: orderId });
            setIsOpen(false);
        }
    };

    // Livreur : aller au dashboard onglet Missions
    const navigateToDriverMissions = () => {
        router.visit('/dashboard-livreur?section=missions');
        setIsOpen(false);
    };

    // Formater la date relative
    const formatRelativeTime = (dateString: string | undefined | null): string => {
        if (dateString == null || dateString === '') return 'Date inconnue';
        let date: Date;
        const dmYMatch = String(dateString).trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{2})/);
        if (dmYMatch) {
            const [, d, m, y, h, min] = dmYMatch;
            date = new Date(Number(y), Number(m) - 1, Number(d), Number(h), Number(min), 0, 0);
        } else {
            date = new Date(dateString);
        }
        if (Number.isNaN(date.getTime())) return 'Date inconnue';
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMs < 0) return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
        if (diffMins < 1) return 'À l\'instant';
        if (diffMins < 60) return diffMins === 1 ? 'Il y a 1 min' : `Il y a ${diffMins} min`;
        if (diffHours < 24) return diffHours === 1 ? 'Il y a 1 h' : `Il y a ${diffHours} h`;
        if (diffDays === 1) return 'Hier';
        if (diffDays < 7) return `Il y a ${diffDays} j`;
        
        return date.toLocaleDateString('fr-FR', { 
            day: 'numeric', 
            month: 'short',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // Obtenir l'icône selon le type de notification
    const getNotificationIcon = (type: string) => {
        switch (type) {
            case 'order':
                return <Package className="size-4" />;
            case 'stock_alert':
                return <AlertTriangle className="size-4" />;
            case 'collaboration':
                return <User className="size-4" />;
            case 'message':
                return <MessageSquare className="size-4" />;
            case 'alert':
                return <AlertTriangle className="size-4" />;
            case 'partner_resource_action':
                return <Package className="size-4" />;
            default:
                return <Info className="size-4" />;
        }
    };

    // Composant Tabs personnalisé
    const CustomTabs = () => (
        <div className="mt-3 flex rounded-lg bg-gradient-to-r from-gray-800 to-black p-1 shadow-inner">
            <button
                type="button"
                className={`flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-all ${activeTab === 'all' ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg' : 'text-gray-300 hover:text-white hover:bg-gray-700/50'}`}
                onClick={() => setActiveTab('all')}
            >
                Toutes ({userNotifications.length})
            </button>
            <button
                type="button"
                className={`flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-all ${activeTab === 'unread' ? 'bg-gradient-to-r from-red-600 to-red-700 text-white shadow-lg' : 'text-gray-300 hover:text-white hover:bg-gray-700/50'}`}
                onClick={() => setActiveTab('unread')}
            >
                Non lues ({partnerUnreadNotifications})
            </button>
        </div>
    );

    return (
        <header className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-3 border-b border-gray-200 bg-gradient-to-r from-white to-gray-50 px-6 shadow-lg transition-all duration-200 ease-in-out dark:border-gray-800 dark:from-gray-900 dark:to-gray-800 md:px-4">
            {/* Sidebar Trigger */}
            <SidebarTrigger className="-ml-1 size-9 shrink-0 rounded-lg border border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100 hover:from-gray-100 hover:to-gray-200 dark:border-gray-700 dark:from-gray-800 dark:to-gray-700 dark:hover:from-gray-700 dark:hover:to-gray-600" />
            
            {/* Breadcrumbs */}
            <div className="flex flex-1 items-center gap-2 min-w-0">
                <Breadcrumbs breadcrumbs={breadcrumbs} />
            </div>

            {/* Alerte stocks (seuil atteint) */}
            {showStockAlert && (
                <Link
                    href="/stocks?alerte_seuil=1"
                    className="group relative flex size-10 shrink-0 items-center justify-center rounded-lg border border-amber-200 bg-gradient-to-r from-amber-50 to-yellow-50 text-amber-700 transition-all duration-300 hover:scale-105 hover:border-amber-300 hover:from-amber-100 hover:to-yellow-100 hover:shadow-lg dark:border-amber-800 dark:from-amber-950/50 dark:to-yellow-950/50 dark:text-amber-400 dark:hover:from-amber-900/50 dark:hover:to-yellow-900/50"
                    title={`${stockAlertsCount} produit(s) au seuil d'alerte de stock`}
                >
                    <Boxes className="size-5 transition-transform group-hover:scale-110" />
                    <span className="absolute -right-1 -top-1 flex min-h-[20px] min-w-[20px] items-center justify-center rounded-full bg-gradient-to-r from-amber-500 to-amber-600 px-1 text-[11px] font-bold text-white shadow-md">
                        {stockAlertsCount > 99 ? '99+' : stockAlertsCount}
                    </span>
                    <span className="sr-only">
                        {stockAlertsCount} produit(s) au seuil d'alerte
                    </span>
                </Link>
            )}

            {/* Bouton Notifications */}
            {showBell && (
                <DropdownMenu
                    open={isOpen}
                    onOpenChange={(open) => {
                        setIsOpen(open);
                        if (open) {
                            if (partnerUnreadNotifications > 0) {
                                setActiveTab('unread');
                            } else {
                                setActiveTab('all');
                            }
                        } else {
                            // À la fermeture : marquer tout comme lu pour réinitialiser le compteur, puis recharger
                            if (partnerUnreadNotifications > 0) {
                                markAllAsRead();
                            } else {
                                sessionStorage.setItem(notificationStorageKey, String(unreadCount));
                                router.reload({
                                    only: ['userNotifications', 'pendingCollaborationRequests', 'alerts'],
                                    preserveScroll: true,
                                });
                            }
                        }
                    }}
                >
                    <DropdownMenuTrigger asChild>
                        <Button
                            variant="ghost"
                            size="icon"
                            className="group relative size-10 shrink-0 rounded-lg border border-transparent bg-gradient-to-r from-gray-50 to-gray-100 hover:border-red-200 hover:from-red-50 hover:to-rose-50 dark:from-gray-800 dark:to-gray-700 dark:hover:border-red-800 dark:hover:from-red-950/30 dark:hover:to-rose-950/30"
                            title={isDriver ? 'Notifications' : 'Notifications et demandes'}
                        >
                            <div className="relative">
                                <Bell className="size-5 text-gray-700 transition-transform group-hover:scale-110 group-hover:text-red-600 dark:text-gray-300 dark:group-hover:text-red-400" />
                                {unreadCount > 0 && (
                                    <>
                                        <span className="absolute -right-1 -top-1 flex min-w-[20px] h-[20px] items-center justify-center rounded-full bg-gradient-to-r from-red-600 to-red-700 px-1 text-[11px] font-bold text-white shadow-lg ring-2 ring-white dark:ring-gray-800">
                                            {unreadCount > 99 ? '99+' : unreadCount}
                                        </span>
                                        <div className="absolute -right-1 -top-1 flex min-w-[20px] h-[20px] animate-ping items-center justify-center rounded-full bg-red-600/70"></div>
                                    </>
                                )}
                            </div>
                            <span className="sr-only">
                                {isDriver ? 'Notifications' : 'Notifications'}
                            </span>
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent 
                        align="end" 
                        className="w-[420px] max-h-[85vh] overflow-hidden p-0 shadow-2xl border-2 border-gray-300 dark:border-gray-700 rounded-xl"
                        sideOffset={8}
                        onCloseAutoFocus={(e) => e.preventDefault()}
                    >
                        {/* En-tête des notifications */}
                        <div className="sticky top-0 z-10 border-b border-gray-300 bg-gradient-to-r from-gray-900 via-black to-gray-900 p-4 dark:border-gray-700 dark:from-gray-950 dark:via-black dark:to-gray-950">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="rounded-full bg-gradient-to-r from-blue-600 to-cyan-600 p-2">
                                        <Bell className="size-5 text-white" />
                                    </div>
                                    <div>
                                        <h3 className="text-lg font-bold text-white">
                                            📢 Centre de notifications
                                        </h3>
                                        <p className="text-sm text-gray-300">
                                            {userName} • {formatRelativeTime(new Date().toISOString())}
                                        </p>
                                    </div>
                                </div>
                                {unreadCount > 0 && (
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        className="text-white hover:bg-white/10 hover:text-white"
                                        onClick={markAllAsRead}
                                    >
                                        <CheckCircle className="mr-2 size-4" />
                                        Tout marquer comme lu
                                    </Button>
                                )}
                            </div>
                            
                            {/* Tabs personnalisés */}
                            <CustomTabs />
                        </div>

                        {/* Contenu des notifications avec défilement personnalisé */}
                        <div className="max-h-[400px] overflow-y-auto bg-gradient-to-b from-white to-gray-50 dark:from-gray-900 dark:to-gray-800">
                            {isDriver ? (
                                // Vue pour livreurs
                                <>
                                    {filteredNotifications.length === 0 ? (
                                        <div className="flex flex-col items-center justify-center p-8 text-center">
                                            <div className="mb-4 flex size-16 items-center justify-center rounded-full bg-gradient-to-r from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900">
                                                <Bell className="size-8 text-gray-400" />
                                            </div>
                                            <p className="font-medium text-gray-900 dark:text-white">
                                                Aucune notification
                                            </p>
                                            <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
                                                Vous serez alerté dès qu'il y aura du nouveau
                                            </p>
                                        </div>
                                    ) : (
                                        <div className="divide-y divide-gray-200 dark:divide-gray-700">
                                            {filteredNotifications.map((notif) => {
                                                const alert = alertConfig[notif.alert ?? 'info'];
                                                const Icon = alert.icon;
                                                const isUnread = !notif.read_at;
                                                
                                                return (
                                                    <div
                                                        key={notif.id}
                                                        className={`relative px-4 py-3 transition-all duration-300 hover:bg-gray-100/50 dark:hover:bg-gray-800/50 ${isUnread ? alert.bgClass : ''} ${isUnread ? 'border-l-4 ' + alert.borderClass.split('border-l-')[1] : ''}`}
                                                    >
                                                        <div className="flex items-start gap-3">
                                                            <div className={`mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-xl ${alert.iconBgClass} ${isUnread ? 'ring-2 ring-offset-2 ring-opacity-50 ' + alert.borderClass.split('border-l-')[1].replace('500', '400') : ''}`}>
                                                                <div className={alert.iconTextClass}>
                                                                    {getNotificationIcon(notif.type)}
                                                                </div>
                                                            </div>
                                                            <div className="min-w-0 flex-1">
                                                                <div className="flex items-center gap-2 mb-1">
                                                                    <Badge
                                                                        variant={alert.badgeVariant}
                                                                        className={`text-xs font-medium px-2 py-0.5 ${alert.textClass} border ${alert.borderClass}`}
                                                                    >
                                                                        <Icon className="mr-1 inline size-3" />
                                                                        {alert.label}
                                                                    </Badge>
                                                                    <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                                                                        <Clock className="mr-1 inline size-3" />
                                                                        {formatRelativeTime(notif.created_at)}
                                                                    </span>
                                                                </div>
                                                                <p className="mt-1 text-sm font-medium text-gray-900 dark:text-white">
                                                                    {notif.message}
                                                                </p>
                                                                {notif.order_id && (
                                                                    <Button
                                                                        variant="link"
                                                                        size="sm"
                                                                        className="mt-2 h-auto p-0 font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400"
                                                                        onClick={(e) => {
                                                                            e.stopPropagation();
                                                                            navigateToDriverMissions();
                                                                        }}
                                                                    >
                                                                        Voir mes missions
                                                                        <ChevronRight className="ml-1 size-3" />
                                                                    </Button>
                                                                )}
                                                            </div>
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                                className="size-7 hover:bg-gray-200 dark:hover:bg-gray-700"
                                                                onClick={() => {
                                                                    router.post(`/notifications/${notif.id}/marquer-lue`, {}, {
                                                                        preserveScroll: true,
                                                                    });
                                                                }}
                                                            >
                                                                <X className="size-4" />
                                                            </Button>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    )}
                                </>
                            ) : (
                                // Vue pour autres rôles
                                <>
                                    {/* Notifications de commandes */}
                                    {filteredNotifications.length > 0 && (
                                        <div className="border-b border-gray-200 dark:border-gray-700">
                                            <div className="px-4 py-3 bg-gradient-to-r from-blue-50 to-cyan-50 dark:from-blue-900/30 dark:to-cyan-900/30">
                                                <div className="flex items-center gap-2">
                                                    <div className="rounded-full bg-gradient-to-r from-blue-600 to-cyan-600 p-1.5">
                                                        <Package className="size-4 text-white" />
                                                    </div>
                                                    <span className="text-sm font-semibold text-gray-900 dark:text-white">
                                                        Activité des commandes
                                                    </span>
                                                    <Badge className="ml-auto bg-gradient-to-r from-blue-600 to-cyan-600 text-white">
                                                        {filteredNotifications.length}
                                                    </Badge>
                                                </div>
                                            </div>
                                            <div className="divide-y divide-gray-200 dark:divide-gray-700">
                                                {filteredNotifications.slice(0, 3).map((notif) => {
                                                    const alert = alertConfig[notif.alert ?? 'info'];
                                                    const Icon = alert.icon;
                                                    const isUnread = !notif.read_at;
                                                    
                                                    return (
                                                        <div
                                                            key={notif.id}
                                                            className={`px-4 py-3 transition-all duration-300 hover:bg-gray-100/50 dark:hover:bg-gray-800/50 ${isUnread ? alert.bgClass : ''}`}
                                                        >
                                                            <div className="flex items-start gap-3">
                                                                <div className={`mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg ${alert.iconBgClass}`}>
                                                                    <Icon className={`size-5 ${alert.iconTextClass}`} />
                                                                </div>
                                                                <div className="min-w-0 flex-1">
                                                                    <div className="flex items-center gap-2 mb-1">
                                                                        <span className={`text-xs font-semibold ${alert.textClass}`}>
                                                                            {alert.label}
                                                                        </span>
                                                                        <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                                                                            {formatRelativeTime(notif.created_at)}
                                                                        </span>
                                                                        {isUnread && (
                                                                            <div className="size-2 rounded-full bg-red-500 animate-pulse"></div>
                                                                        )}
                                                                    </div>
                                                                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                                                                        {notif.message}
                                                                    </p>
                                                                    {notif.order_id && (
                                                                        <Button
                                                                            variant="link"
                                                                            size="sm"
                                                                            className="mt-2 h-auto p-0 font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400"
                                                                            onClick={() => navigateToOrder(notif.order_id)}
                                                                        >
                                                                            Voir la commande
                                                                            <ChevronRight className="ml-1 size-3" />
                                                                        </Button>
                                                                    )}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                            {filteredNotifications.length > 3 && (
                                                <div className="px-4 py-2 border-t border-gray-200 dark:border-gray-700 bg-gradient-to-r from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-700">
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="w-full text-blue-600 hover:text-blue-700 dark:text-blue-400 font-medium"
                                                        onClick={() => {
                                                            router.get('/notifications');
                                                            setIsOpen(false);
                                                        }}
                                                    >
                                                        Voir toutes les notifications ({filteredNotifications.length})
                                                        <ChevronRight className="ml-2 size-3" />
                                                    </Button>
                                                </div>
                                            )}
                                        </div>
                                    )}

                                    {/* Demandes de collaboration */}
                                    {pendingCollaborationRequests.length > 0 && (
                                        <div className="border-t-2 border-green-500">
                                            <div className="px-4 py-3 bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-900/30 dark:to-emerald-900/30">
                                                <div className="flex items-center gap-2">
                                                    <div className="rounded-full bg-gradient-to-r from-green-600 to-emerald-600 p-1.5">
                                                        <User className="size-4 text-white" />
                                                    </div>
                                                    <span className="text-sm font-semibold text-gray-900 dark:text-white">
                                                        Demandes de collaboration
                                                    </span>
                                                    <Badge className="ml-auto bg-gradient-to-r from-green-600 to-emerald-600 text-white">
                                                        {pendingCollaborationRequests.length}
                                                    </Badge>
                                                </div>
                                            </div>
                                            <div className="divide-y divide-gray-200 dark:divide-gray-700">
                                                {pendingCollaborationRequests.map((req) => (
                                                    <div
                                                        key={req.id}
                                                        className="px-4 py-3 transition-all duration-300 hover:bg-gray-100/50 dark:hover:bg-gray-800/50"
                                                    >
                                                        <div className="flex items-start gap-3">
                                                            <div className="mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-r from-blue-600 to-blue-700 p-2">
                                                                <User className="size-5 text-white" />
                                                            </div>
                                                            <div className="min-w-0 flex-1">
                                                                <div className="flex items-center gap-2 mb-1">
                                                                    <p className="text-sm font-semibold text-gray-900 dark:text-white">
                                                                        {req.from_partner_name}
                                                                    </p>
                                                                    <Badge variant="outline" className="text-xs border-blue-300 text-blue-700 dark:border-blue-700 dark:text-blue-400">
                                                                        {req.type_label}
                                                                    </Badge>
                                                                    <span className="ml-auto text-xs text-gray-500 dark:text-gray-400">
                                                                        {formatRelativeTime(req.created_at)}
                                                                    </span>
                                                                </div>
                                                                <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
                                                                    Nouvelle demande de collaboration
                                                                </p>
                                                                <div className="flex gap-2">
                                                                    <Button
                                                                        size="sm"
                                                                        className="flex-1 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white shadow-md"
                                                                        onClick={() => {
                                                                            router.post(`/demandes-collaboration/${req.id}/accept`, {}, {
                                                                                preserveScroll: true,
                                                                                onSuccess: () => setIsOpen(false),
                                                                            });
                                                                        }}
                                                                    >
                                                                        <CheckCircle className="mr-2 size-4" />
                                                                        Accepter
                                                                    </Button>
                                                                    <Button
                                                                        size="sm"
                                                                        variant="outline"
                                                                        className="flex-1 border-red-300 text-red-700 hover:bg-gradient-to-r hover:from-red-50 hover:to-rose-50 hover:text-red-800 dark:border-red-700 dark:text-red-400 dark:hover:from-red-900/30 dark:hover:to-rose-900/30"
                                                                        onClick={() => {
                                                                            router.post(`/demandes-collaboration/${req.id}/refuse`, {}, {
                                                                                preserveScroll: true,
                                                                                onSuccess: () => setIsOpen(false),
                                                                            });
                                                                        }}
                                                                    >
                                                                        <X className="mr-2 size-4" />
                                                                        Refuser
                                                                    </Button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    {/* Aucune notification */}
                                    {filteredNotifications.length === 0 && pendingCollaborationRequests.length === 0 && (
                                        <div className="flex flex-col items-center justify-center p-8 text-center">
                                            <div className="mb-4 flex size-16 items-center justify-center rounded-full bg-gradient-to-r from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900">
                                                <Bell className="size-8 text-gray-400" />
                                            </div>
                                            <p className="font-medium text-gray-900 dark:text-white">
                                                Aucune notification
                                            </p>
                                            <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
                                                Vous êtes à jour avec toutes les activités
                                            </p>
                                        </div>
                                    )}
                                </>
                            )}
                        </div>

                        {/* Pied de page */}
                        <div className="sticky bottom-0 border-t-2 border-gray-300 bg-gradient-to-r from-gray-900 to-black p-3 dark:border-gray-700 dark:from-gray-950 dark:to-black">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className={`flex size-8 items-center justify-center rounded-full ${unreadCount > 0 ? 'bg-gradient-to-r from-red-600 to-red-700' : 'bg-gradient-to-r from-green-600 to-green-700'}`}>
                                        <span className="text-xs font-bold text-white">
                                            {unreadCount > 99 ? '99+' : unreadCount}
                                        </span>
                                    </div>
                                    <div>
                                        <p className="text-sm font-semibold text-white">
                                            {unreadCount === 0 ? '🎉 Tout est lu' : `${unreadCount} notification${unreadCount > 1 ? 's' : ''} non lue${unreadCount > 1 ? 's' : ''}`}
                                        </p>
                                        <p className="text-xs text-gray-300">
                                            Dernière mise à jour: {formatRelativeTime(new Date().toISOString())}
                                        </p>
                                    </div>
                                </div>
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="text-white hover:bg-white/10 hover:text-white"
                                    onClick={() => {
                                        router.get('/notifications');
                                        setIsOpen(false);
                                    }}
                                >
                                    Voir toutes
                                    <ChevronRight className="ml-1 size-4" />
                                </Button>
                            </div>
                        </div>
                    </DropdownMenuContent>
                </DropdownMenu>
            )}
        </header>
    );
}