import { usePage, Link, router } from '@inertiajs/react';
import { Bell } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
import { SharedData, Notification } from '@/types';

// Importar rutas de Wayfinder
import { read as markRead, readAll as markAllReadRoute } from '@/routes/notifications';
import { show as threadShow } from '@/routes/forum/thread';

export function NotificationsDropdown() {
    const { auth } = usePage<SharedData>().props;
    
    // Obtenemos notificaciones directamente de las props de Inertia
    const notifications = (auth.notifications || []) as Notification[];
    const unreadCount = auth.notificationsCount || 0;

    const markAllRead = () => {
        router.post(markAllReadRoute().url, {}, {
            preserveScroll: true,
        });
    };

    const markAsRead = (id: string) => {
        router.post(markRead({ id }).url, {}, {
            preserveScroll: true,
        });
    };

    if (!auth.user) return null;

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="relative text-muted-foreground hover:text-foreground">
                    <Bell className="h-5 w-5" />
                    {unreadCount > 0 && (
                        <span className="absolute top-2 right-2 h-2.5 w-2.5 rounded-full bg-red-600 ring-2 ring-background animate-pulse" />
                    )}
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-80 p-0">
                <div className="flex items-center justify-between px-4 py-3 border-b text-sm font-semibold bg-muted/20">
                    <span>Notificaciones</span>
                    {unreadCount > 0 && (
                        <Button 
                            variant="ghost" 
                            className="h-auto py-1 px-2 text-xs text-primary hover:text-primary/80" 
                            onClick={(e) => {
                                e.preventDefault();
                                markAllRead();
                            }}
                        >
                            Marcar leídas
                        </Button>
                    )}
                </div>
                <ScrollArea className="h-[300px]">
                    {notifications.length === 0 ? (
                        <div className="p-8 text-center text-sm text-muted-foreground flex flex-col items-center gap-2">
                            <Bell className="h-8 w-8 opacity-20" />
                            <p>No tienes notificaciones nuevas</p>
                        </div>
                    ) : (
                        <div className="divide-y">
                            {notifications.map((notification) => (
                                <DropdownMenuItem key={notification.id} className="p-0 cursor-pointer focus:bg-accent focus:text-accent-foreground" asChild>
                                    <Link 
                                        href={threadShow.url({ 
                                            forum: notification.data.forum_slug, 
                                            thread: notification.data.thread_slug 
                                        })}
                                        onClick={() => markAsRead(notification.id)}
                                        className="flex gap-3 items-start w-full p-4 transition-colors hover:bg-muted/50"
                                    >
                                        <Avatar className="h-8 w-8 mt-1 shrink-0">
                                            <AvatarImage src={notification.data.user_avatar} />
                                            <AvatarFallback>{notification.data.user_name?.charAt(0)}</AvatarFallback>
                                        </Avatar>
                                        <div className="flex-1 space-y-1">
                                            <p className="text-sm leading-snug">
                                                <span className="font-semibold text-foreground">{notification.data.user_name}</span>{' '}
                                                <span className="text-muted-foreground">{notification.data.message}</span>
                                            </p>
                                            <p className="text-xs text-muted-foreground capitalize">
                                                {formatDistanceToNow(new Date(notification.created_at), { addSuffix: true, locale: es })}
                                            </p>
                                        </div>
                                        {!notification.read_at && (
                                            <span className="h-2 w-2 rounded-full bg-blue-500 shrink-0 mt-2" />
                                        )}
                                    </Link>
                                </DropdownMenuItem>
                            ))}
                        </div>
                    )}
                </ScrollArea>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
