import { Head, router, usePage } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import {
    AlertCircle,
    Bell,
    CheckCircle,
    ChevronRight,
    Clock,
    Info,
    Package,
    User,
    MessageSquare,
    AlertTriangle,
    XCircle,
    X,
    MailOpen,
    Filter,
    CheckCheck,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import type { SharedData } from '@/types';

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;
    collaboration_request_id?: number | null;
    /** true si la demande de collaboration est encore en attente (boutons Accepter/Refuser affichés). */
    collaboration_request_pending?: boolean;
    /** Action (created / updated / deleted) pour partner_resource_action. */
    action?: string | null;
    /** Ancienne valeur en cas de modification. */
    old_value?: Record<string, unknown> | null;
    /** Nouvelle valeur en cas de modification. */
    new_value?: Record<string, unknown> | null;
};

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

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

const VALUE_LABELS: Record<string, string> = {
    status: 'Statut',
    driver_id: 'Livreur',
    name: 'Nom',
    description: 'Description',
    product_type: 'Type produit',
    unit: 'Unité',
    price: 'Prix',
    is_active: 'Actif',
    image_path: 'Image',
    quantity_available: 'Quantité disponible',
    reorder_level: 'Seuil de réappro.',
};

const STATUS_LABELS: Record<string, string> = {
    attente: 'En attente',
    en_cours: 'En cours',
    livree: 'Livrée',
    echouee: 'Échouée',
};

function formatValueDisplay(val: unknown, key?: string): string {
    if (val === null || val === undefined) return '—';
    if (key === 'status' && typeof val === 'string' && STATUS_LABELS[val]) return STATUS_LABELS[val];
    if (typeof val === 'boolean') return val ? 'Oui' : 'Non';
    if (typeof val === 'object' && !Array.isArray(val)) return JSON.stringify(val);
    return String(val);
}

function formatNotificationValue(obj: Record<string, unknown> | null | undefined): { label: string; value: string }[] {
    if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return [];
    return Object.entries(obj)
        .filter(([, v]) => v !== undefined && v !== null)
        .map(([key, value]) => ({
            label: VALUE_LABELS[key] ?? key,
            value: formatValueDisplay(value, key),
        }));
}

function parseDateForSort(dateString: string | undefined | null): Date {
    if (dateString == null || dateString === '') return new Date(0);
    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;
        return new Date(Number(y), Number(m) - 1, Number(d), Number(h), Number(min), 0, 0);
    }
    const date = new Date(dateString);
    return Number.isNaN(date.getTime()) ? new Date(0) : date;
}

function formatRelativeTime(dateString: string | undefined | null): string {
    if (dateString == null || dateString === '') return 'Date inconnue';
    const dmYMatch = String(dateString).trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{2})/);
    let date: Date;
    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' });
}

function getNotificationIcon(type: string) {
    switch (type) {
        case 'order':
            return <Package className="size-5" />;
        case 'stock_alert':
            return <AlertTriangle className="size-5" />;
        case 'collaboration':
            return <User className="size-5" />;
        case 'message':
            return <MessageSquare className="size-5" />;
        case 'alert':
            return <AlertTriangle className="size-5" />;
        case 'partner_resource_action':
            return <Package className="size-5" />;
        default:
            return <Info className="size-5" />;
    }
}

export default function NotificationsIndex() {
    const {
        auth,
        userNotifications = [],
        pendingCollaborationRequests = [],
    } = usePage<SharedData>().props as {
        auth?: { user?: { role?: string; name?: string } };
        userNotifications?: UserNotification[];
        pendingCollaborationRequests?: PendingRequest[];
    };

    const [activeTab, setActiveTab] = useState<'all' | 'unread'>('all');
    const [filter, setFilter] = useState<string>('all');
    const isDriver = auth?.user?.role === 'livreur';
    const unreadCount = userNotifications.filter((n) => !n.read_at).length;

    // Tri: plus récent en premier (created_at décroissant)
    const sortedNotifications = useMemo(() => {
        return [...userNotifications].sort((a, b) => {
            const dateA = parseDateForSort(a.created_at);
            const dateB = parseDateForSort(b.created_at);
            return dateB.getTime() - dateA.getTime();
        });
    }, [userNotifications]);

    const filteredNotifications = useMemo(() => {
        let notifications = sortedNotifications;
        
        if (activeTab === 'unread') {
            notifications = notifications.filter((n) => !n.read_at);
        }
        
        if (filter !== 'all') {
            notifications = notifications.filter((n) => n.type === filter);
        }
        
        return notifications;
    }, [sortedNotifications, activeTab, filter]);

    const markAllAsRead = () => {
        if (isDriver) {
            router.post('/livreur/notifications/marquer-lues', {}, { preserveScroll: true });
        } else {
            router.post('/notifications/marquer-lues', {}, { preserveScroll: true });
        }
    };

    const navigateToOrder = (orderId?: number | null) => {
        if (orderId) {
            router.get('/commandes', { order_id: orderId });
        }
    };

    const navigateToDriverMissions = () => {
        router.visit('/dashboard-livreur?section=missions');
    };

    const breadcrumbs: BreadcrumbItem[] = [{ title: 'Notifications', href: '/notifications' }];

    // Types de notifications uniques pour le filtre
    const notificationTypes = useMemo(() => {
        const types = new Set(sortedNotifications.map(n => n.type));
        return Array.from(types);
    }, [sortedNotifications]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Notifications" />
            
            <div className="space-y-8">
                
                {/* Contenu principal */}
                <Card className="shadow-xl border-2 border-gray-100 dark:border-gray-800">
                    <CardHeader className="space-y-4 bg-gradient-to-r from-gray-50 to-white dark:from-gray-900 dark:to-gray-800 border-b">
                        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                            <div className="flex items-center gap-3">
                                <div className="rounded-full bg-blue-100 dark:bg-blue-900/40 p-3">
                                    <Bell className="size-6 text-blue-600 dark:text-blue-400" />
                                </div>
                                <div>
                                    <CardTitle className="text-2xl font-bold text-gray-900 dark:text-white">
                                        Centre de notifications
                                    </CardTitle>
                                    <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                                        Gérez toutes vos alertes et messages en un seul endroit
                                    </p>
                                </div>
                            </div>
                            
                            <div className="flex flex-wrap gap-2">
                                {unreadCount > 0 && (
                                    <Button 
                                        onClick={markAllAsRead}
                                        className="bg-blue-600 hover:bg-blue-700 text-white shadow-md"
                                    >
                                        <CheckCheck className="mr-2 size-4" />
                                        Tout marquer comme lu
                                    </Button>
                                )}
                                <Button 
                                    variant="outline" 
                                    className="border-red-300 text-red-600 hover:bg-red-50 hover:text-red-700 dark:border-red-700 dark:text-red-400"
                                >
                                    <Filter className="mr-2 size-4" />
                                    Filtrer
                                </Button>
                            </div>
                        </div>

                        {/* Onglets et filtres */}
                        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                            {/* Onglets personnalisés */}
                            <div className="flex rounded-lg bg-gray-100 dark:bg-gray-800 p-1">
                                <button
                                    type="button"
                                    onClick={() => setActiveTab('all')}
                                    className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                                        activeTab === 'all'
                                            ? 'bg-white text-gray-900 shadow-sm dark:bg-gray-700 dark:text-white'
                                            : 'text-gray-600 hover:text-gray-900 dark:text-gray-400'
                                    }`}
                                >
                                    Toutes {/*({userNotifications.length})*/}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setActiveTab('unread')}
                                    className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                                        activeTab === 'unread'
                                            ? 'bg-red-100 text-red-700 shadow-sm dark:bg-red-900/30 dark:text-red-400'
                                            : 'text-gray-600 hover:text-gray-900 dark:text-gray-400'
                                    }`}
                                >
                                    Non lues ({unreadCount})
                                </button>
                            </div>

                            {/* Filtres par type */}
                            <div className="flex flex-wrap gap-2">
                                <Button
                                    variant={filter === 'all' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setFilter('all')}
                                    className={filter === 'all' ? 'bg-black text-white hover:bg-gray-800' : ''}
                                >
                                    Tous types
                                </Button>
                                {notificationTypes.map(type => (
                                    <Button
                                        key={type}
                                        variant={filter === type ? 'default' : 'outline'}
                                        size="sm"
                                        onClick={() => setFilter(type)}
                                        className={filter === type ? 'bg-blue-600 text-white hover:bg-blue-700' : ''}
                                    >
                                        {type === 'order' && <Package className="mr-1 size-3" />}
                                        {type === 'message' && <MessageSquare className="mr-1 size-3" />}
                                        {type.charAt(0).toUpperCase() + type.slice(1)}
                                    </Button>
                                ))}
                            </div>
                        </div>
                    </CardHeader>

                    <CardContent className="p-0">
                        {/* Liste des notifications */}
                        <div className="divide-y divide-gray-100 dark:divide-gray-800">
                            {filteredNotifications.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-20 text-center">
                                    <div className="mb-6 flex size-20 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-10 text-gray-400 dark:text-gray-500" />
                                    </div>
                                    <p className="text-xl font-semibold text-gray-900 dark:text-white">
                                        {activeTab === 'unread' ? 'Aucune notification non lue' : 'Aucune notification trouvée'}
                                    </p>
                                    <p className="mt-2 text-gray-600 dark:text-gray-400 max-w-md">
                                        {activeTab === 'unread' 
                                            ? 'Toutes vos notifications sont lues. Vous serez alerté dès qu\'il y aura du nouveau.' 
                                            : 'Aucune notification ne correspond à vos filtres. Essayez de modifier vos critères.'}
                                    </p>
                                    {filter !== 'all' && (
                                        <Button 
                                            onClick={() => setFilter('all')}
                                            className="mt-4 bg-blue-600 hover:bg-blue-700"
                                        >
                                            Réinitialiser les filtres
                                        </Button>
                                    )}
                                </div>
                            ) : (
                                filteredNotifications.map((notif) => {
                                    const alert = alertConfig[notif.alert ?? 'info'];
                                    const AlertIcon = alert.icon;
                                    const isUnread = !notif.read_at;
                                    
                                    return (
                                        <div
                                            key={notif.id}
                                            className={`relative px-6 py-5 transition-all duration-200 hover:bg-gray-50 dark:hover:bg-gray-900/50 ${isUnread ? alert.bgClass : ''} ${isUnread ? 'animate-pulse-subtle' : ''}`}
                                        >
                                            <div className="flex items-start gap-4">
                                                {/* Icône de notification */}
                                                <div className={`mt-1 flex size-12 shrink-0 items-center justify-center rounded-xl ${alert.iconBgClass} ${isUnread ? 'ring-2 ring-offset-2 ring-opacity-50' : ''} ${
                                                    isUnread && notif.alert === 'destructive' ? 'ring-red-500' :
                                                    isUnread && notif.alert === 'warning' ? 'ring-yellow-500' :
                                                    isUnread && notif.alert === 'success' ? 'ring-green-500' :
                                                    isUnread ? 'ring-blue-500' : ''
                                                }`}>
                                                    <div className={alert.iconTextClass}>
                                                        {getNotificationIcon(notif.type)}
                                                    </div>
                                                </div>

                                                {/* Contenu de la notification */}
                                                <div className="min-w-0 flex-1">
                                                    <div className="flex flex-wrap items-center gap-2 mb-2">
                                                        <Badge 
                                                            variant={alert.badgeVariant} 
                                                            className={`font-medium px-3 py-1 ${alert.textClass} border ${alert.borderClass}`}
                                                        >
                                                            <AlertIcon className="mr-1 size-3 inline" />
                                                            {alert.label}
                                                        </Badge>
                                                        
                                                        <span className="text-sm font-medium text-gray-900 dark:text-white">
                                                            {formatRelativeTime(notif.created_at)}
                                                        </span>
                                                        
                                                        {isUnread && (
                                                            <span className="inline-flex items-center gap-1 rounded-full bg-red-100 dark:bg-red-900/40 px-2 py-1 text-xs font-medium text-red-700 dark:text-red-300">
                                                                <span className="size-1.5 animate-pulse rounded-full bg-red-500" />
                                                                Non lu
                                                            </span>
                                                        )}
                                                    </div>
                                                    
                                                    <p className="text-base font-medium text-gray-900 dark:text-white leading-relaxed">
                                                        {notif.message}
                                                    </p>

                                                    {notif.type === 'partner_resource_action' && notif.action === 'updated' && (notif.old_value || notif.new_value) && (
                                                        <div className="mt-3 grid gap-3 sm:grid-cols-2">
                                                            {notif.old_value && Object.keys(notif.old_value).length > 0 && (
                                                                <div className="rounded-lg border border-amber-200 bg-amber-50/50 p-3 dark:border-amber-800 dark:bg-amber-950/20">
                                                                    <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-400">Ancienne valeur</p>
                                                                    <dl className="space-y-1 text-sm">
                                                                        {formatNotificationValue(notif.old_value as Record<string, unknown>).map(({ label, value }) => (
                                                                            <div key={label} className="flex justify-between gap-2">
                                                                                <dt className="text-gray-600 dark:text-gray-400">{label}</dt>
                                                                                <dd className="font-medium text-gray-900 dark:text-white truncate" title={value}>{value}</dd>
                                                                            </div>
                                                                        ))}
                                                                    </dl>
                                                                </div>
                                                            )}
                                                            {notif.new_value && Object.keys(notif.new_value).length > 0 && (
                                                                <div className="rounded-lg border border-green-200 bg-green-50/50 p-3 dark:border-green-800 dark:bg-green-950/20">
                                                                    <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-green-700 dark:text-green-400">Nouvelle valeur</p>
                                                                    <dl className="space-y-1 text-sm">
                                                                        {formatNotificationValue(notif.new_value as Record<string, unknown>).map(({ label, value }) => (
                                                                            <div key={label} className="flex justify-between gap-2">
                                                                                <dt className="text-gray-600 dark:text-gray-400">{label}</dt>
                                                                                <dd className="font-medium text-gray-900 dark:text-white truncate" title={value}>{value}</dd>
                                                                            </div>
                                                                        ))}
                                                                    </dl>
                                                                </div>
                                                            )}
                                                        </div>
                                                    )}
                                                    
                                                    {notif.order_id && (
                                                        <Button
                                                            variant="link"
                                                            className={`mt-3 h-auto p-0 font-medium ${
                                                                notif.alert === 'destructive' ? 'text-red-600 hover:text-red-800 dark:text-red-400' :
                                                                notif.alert === 'warning' ? 'text-yellow-600 hover:text-yellow-800 dark:text-yellow-400' :
                                                                notif.alert === 'success' ? 'text-green-600 hover:text-green-800 dark:text-green-400' :
                                                                'text-blue-600 hover:text-blue-800 dark:text-blue-400'
                                                            }`}
                                                            onClick={() =>
                                                                isDriver ? navigateToDriverMissions() : navigateToOrder(notif.order_id)
                                                            }
                                                        >
                                                            {isDriver ? 'Voir mes missions' : 'Voir la commande'}
                                                            <ChevronRight className="ml-1 size-4" />
                                                        </Button>
                                                    )}
                                                    {!isDriver && notif.type === 'collaboration' && notif.collaboration_request_id && notif.collaboration_request_pending && (
                                                        <div className="mt-3 flex flex-wrap gap-2">
                                                            <Button
                                                                size="sm"
                                                                className="bg-green-600 hover:bg-green-700 text-white"
                                                                onClick={() => router.post(`/demandes-collaboration/${notif.collaboration_request_id}/accept`, {}, { preserveScroll: true })}
                                                            >
                                                                <CheckCircle className="mr-2 size-4" />
                                                                Accepter
                                                            </Button>
                                                            <Button
                                                                size="sm"
                                                                variant="outline"
                                                                className="border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-400"
                                                                onClick={() => router.post(`/demandes-collaboration/${notif.collaboration_request_id}/refuse`, {}, { preserveScroll: true })}
                                                            >
                                                                <XCircle className="mr-2 size-4" />
                                                                Refuser
                                                            </Button>
                                                        </div>
                                                    )}
                                                </div>

                                                {/* Actions */}
                                                <div className="flex flex-col items-end gap-2">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 hover:bg-gray-200 dark:hover:bg-gray-800"
                                                        onClick={() => {
                                                            router.post(`/notifications/${notif.id}/marquer-lue`, {}, { preserveScroll: true });
                                                        }}
                                                        title="Marquer comme lu"
                                                    >
                                                        <CheckCircle className="size-4 text-gray-500 hover:text-green-600" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 hover:bg-gray-200 dark:hover:bg-gray-800"
                                                        onClick={() => {
                                                            // Action de suppression
                                                        }}
                                                        title="Supprimer"
                                                    >
                                                        <X className="size-4 text-gray-500 hover:text-red-600" />
                                                    </Button>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </div>

                        {/* Demandes de collaboration */}
                        {!isDriver && pendingCollaborationRequests.length > 0 && (
                            <div className="border-t-4 border-green-500">
                                <div className="px-6 py-4 bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-full bg-green-100 dark:bg-green-900/40 p-2">
                                            <User className="size-5 text-green-600 dark:text-green-400" />
                                        </div>
                                        <div className="flex items-center gap-3">
                                            <span className="text-lg font-semibold text-gray-900 dark:text-white">
                                                Demandes de collaboration en attente
                                            </span>
                                            <Badge className="bg-green-600 hover:bg-green-700 text-white">
                                                {pendingCollaborationRequests.length}
                                            </Badge>
                                        </div>
                                    </div>
                                </div>
                                
                                <div className="divide-y divide-gray-100 dark:divide-gray-800">
                                    {pendingCollaborationRequests.map((req) => (
                                        <div key={req.id} className="px-6 py-5 hover:bg-gray-50 dark:hover:bg-gray-900/30">
                                            <div className="flex items-start gap-4">
                                                <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-gradient-to-r from-blue-100 to-blue-200 dark:from-blue-900/40 dark:to-blue-800/40">
                                                    <User className="size-6 text-blue-600 dark:text-blue-400" />
                                                </div>
                                                
                                                <div className="min-w-0 flex-1">
                                                    <div className="flex items-center gap-3 mb-2">
                                                        <p className="text-lg font-semibold text-gray-900 dark:text-white">
                                                            {req.from_partner_name}
                                                        </p>
                                                        <Badge variant="outline" className="border-blue-300 text-blue-700 dark:border-blue-700 dark:text-blue-400">
                                                            {req.type_label}
                                                        </Badge>
                                                        <span className="text-sm text-gray-500 dark:text-gray-400">
                                                            {formatRelativeTime(req.created_at)}
                                                        </span>
                                                    </div>
                                                    
                                                    <p className="text-gray-700 dark:text-gray-300 mb-4">
                                                        Nouvelle demande de collaboration. Acceptez ou refusez cette demande.
                                                    </p>
                                                    
                                                    <div className="flex flex-wrap gap-3">
                                                        <Button
                                                            size="sm"
                                                            className="bg-green-600 hover:bg-green-700 text-white shadow-md"
                                                            onClick={() => router.post(`/demandes-collaboration/${req.id}/accept`, {})}
                                                        >
                                                            <CheckCircle className="mr-2 size-4" />
                                                            Accepter la collaboration
                                                        </Button>
                                                        <Button
                                                            size="sm"
                                                            variant="outline"
                                                            className="border-red-300 text-red-600 hover:bg-red-50 hover:text-red-700 dark:border-red-700 dark:text-red-400 dark:hover:bg-red-900/30"
                                                            onClick={() => router.post(`/demandes-collaboration/${req.id}/refuse`, {})}
                                                        >
                                                            <X className="mr-2 size-4" />
                                                            Refuser
                                                        </Button>
                                                        <Button
                                                            size="sm"
                                                            variant="ghost"
                                                            className="text-gray-600 hover:text-gray-900 dark:text-gray-400"
                                                        >
                                                            <Info className="mr-2 size-4" />
                                                            Plus d'infos
                                                        </Button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}