import { useState } from 'react';
import { Link } from '@inertiajs/react';
import { BellAlertIcon } from '@heroicons/react/24/solid';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useList } from '@/hooks/useResource';

interface TaskNotification {
    id: string;
    read_at: string | null;
    created_at: string;
    data: { url?: string; message: string; title?: string; board_id?: number };
}

export function NotificationBell() {
    const [open, setOpen] = useState(false);
    const qc = useQueryClient();
    const { data } = useList<TaskNotification>('notifications', '/notifications');
    const notifications = (data as unknown as { data: TaskNotification[]; unread_count: number } | undefined);
    const unreadCount = notifications?.unread_count ?? 0;

    const markAllRead = useMutation({
        mutationFn: () => api.post('/notifications/read-all'),
        onSuccess: () => qc.invalidateQueries({ queryKey: ['notifications'] }),
    });

    const markRead = useMutation({
        mutationFn: (id: string) => api.post(`/notifications/${id}/read`),
        onSuccess: () => qc.invalidateQueries({ queryKey: ['notifications'] }),
    });

    return (
        <div className="relative">
            <button
                onClick={() => setOpen((v) => !v)}
                className="relative p-2 rounded-lg text-gray-500 hover:bg-gray-100"
                title="Notifikasi tugas"
            >
                <BellAlertIcon className="w-5 h-5" />
                {unreadCount > 0 && (
                    <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 flex items-center justify-center rounded-full bg-red-500 text-white text-[10px] font-semibold leading-none">
                        {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                )}
            </button>

            {open && (
                <>
                    <div className="fixed inset-0 z-20" onClick={() => setOpen(false)} />
                    <div className="absolute right-0 top-full mt-2 w-80 bg-white border border-gray-200 rounded-xl shadow-lg py-2 z-30 max-h-96 overflow-y-auto">
                        <div className="flex items-center justify-between px-4 py-1.5">
                            <span className="text-sm font-semibold text-gray-800">Notifikasi</span>
                            {unreadCount > 0 && (
                                <button
                                    onClick={() => markAllRead.mutate()}
                                    className="text-xs text-sky-600 hover:underline"
                                >
                                    Tandai semua dibaca
                                </button>
                            )}
                        </div>
                        <div className="my-1 border-t border-gray-100" />
                        {(!notifications?.data || notifications.data.length === 0) && (
                            <p className="px-4 py-4 text-sm text-gray-400 text-center">Belum ada notifikasi</p>
                        )}
                        {notifications?.data.map((n) => (
                            <Link
                                key={n.id}
                                href={n.data.url ?? (n.data.board_id ? `/board/${n.data.board_id}` : '/dashboard')}
                                onClick={() => { setOpen(false); if (!n.read_at) markRead.mutate(n.id); }}
                                className={`block px-4 py-2.5 text-sm hover:bg-gray-50 ${!n.read_at ? 'bg-sky-50/60' : ''}`}
                            >
                                <p className="text-gray-700">{n.data.message}</p>
                                <p className="text-xs text-gray-400 mt-0.5">{new Date(n.created_at).toLocaleString('id-ID')}</p>
                            </Link>
                        ))}
                    </div>
                </>
            )}
        </div>
    );
}
