import { Link, router } from '@inertiajs/react';
import { Bell } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { formatDate } from '@/lib/utils';
import NotificationController from '@/actions/App/Http/Controllers/Admin/NotificationController';
import { edit as editNotifications } from '@/routes/notifications';

type NotificationItem = {
    id: string;
    data: {
        message: string;
        url: string;
        code?: string;
        start_date?: string;
        end_date?: string;
    };
    read_at: string | null;
    created_at: string | null;
};

export function NotificationBell() {
    const [open, setOpen] = useState(false);
    const [notifications, setNotifications] = useState<NotificationItem[]>([]);
    const [unreadCount, setUnreadCount] = useState(0);

    function refresh() {
        fetch(NotificationController.index.url(), {
            headers: { Accept: 'application/json' },
        })
            .then((response) => response.json())
            .then(
                (payload: {
                    notifications: NotificationItem[];
                    unread_count: number;
                }) => {
                    setNotifications(payload.notifications ?? []);
                    setUnreadCount(payload.unread_count ?? 0);
                },
            )
            .catch(() => {
                setNotifications([]);
                setUnreadCount(0);
            });
    }

    useEffect(() => {
        refresh();
    }, []);

    function handleOpenChange(nextOpen: boolean) {
        setOpen(nextOpen);
        if (nextOpen) {
            refresh();
        }
    }

    function openNotification(notification: NotificationItem) {
        router.post(
            NotificationController.markAsRead.url(notification.id),
            {},
            {
                preserveScroll: true,
                onFinish: () => {
                    router.visit(notification.data.url);
                },
            },
        );
    }

    function markAllAsRead() {
        router.post(
            NotificationController.markAllAsRead.url(),
            {},
            { preserveScroll: true, onSuccess: refresh },
        );
    }

    return (
        <DropdownMenu open={open} onOpenChange={handleOpenChange}>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="relative">
                    <Bell className="size-5" />
                    {unreadCount > 0 && (
                        <Badge
                            className="absolute -top-1 -right-1 h-4 min-w-4 justify-center border-0 bg-brand-yellow px-1 text-[10px] text-brand-yellow-foreground"
                        >
                            {unreadCount > 9 ? '9+' : unreadCount}
                        </Badge>
                    )}
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-80">
                <div className="flex items-center justify-between px-2 py-1.5">
                    <DropdownMenuLabel className="p-0">
                        Notifications
                    </DropdownMenuLabel>
                    {unreadCount > 0 && (
                        <Button
                            variant="link"
                            size="sm"
                            className="h-auto p-0 text-xs"
                            onClick={markAllAsRead}
                        >
                            Tout marquer comme lu
                        </Button>
                    )}
                </div>
                <DropdownMenuSeparator />
                {notifications.length === 0 ? (
                    <p className="text-muted-foreground px-2 py-4 text-center text-sm">
                        Aucune notification.
                    </p>
                ) : (
                    notifications.map((notification) => (
                        <DropdownMenuItem
                            key={notification.id}
                            className="flex flex-col items-start gap-0.5"
                            onSelect={() => openNotification(notification)}
                        >
                            <span
                                className={
                                    notification.read_at
                                        ? 'text-muted-foreground text-sm'
                                        : 'text-sm font-medium'
                                }
                            >
                                {notification.data.message}
                            </span>
                            {notification.created_at && (
                                <span className="text-muted-foreground text-xs">
                                    {formatDate(notification.created_at)}
                                </span>
                            )}
                        </DropdownMenuItem>
                    ))
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem asChild className="justify-center text-sm">
                    <Link href={editNotifications()}>
                        Voir toutes les notifications
                    </Link>
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
