import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Bell } from "lucide-react";
import { useTranslations } from "next-intl";
import { useGet } from "@/hooks/use-get";
import { useFormSubmission } from "@/hooks/use-form-submission";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/cn";
import { Button } from "@/components/ui/button";
import { useRouter } from "@/i18n/navigation";
import { useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { ar, enUS } from "date-fns/locale";
import { useLocale } from "next-intl";

interface Notification {
    id: number;
    title: string;
    body: string;
    image: string | null;
    url: string;
    read_at: string | null;
    created_at: string;
    data: any;
}

export function Notifications() {
    const t = useTranslations();
    const router = useRouter();
    const locale = useLocale();
    const [isOpen, setIsOpen] = useState(false);

    const { data: notificationsData, refetch } = useGet({
        url: "/user/notifications",
        context: "dashboard"
    });

    const notifications: Notification[] = notificationsData?.data || [];
    const unreadCount = notifications.filter(n => !n.read_at).length;

    const markAsReadMutation = useFormSubmission({
        endPoint: "/user/notifications/read",
        method: "POST",
        onSuccess: () => {
            refetch();
        }
    });


    const handleMarkAsRead = (e: React.MouseEvent, id: number) => {
        e.stopPropagation();
        markAsReadMutation.mutate({ id });
    };

    return (
        <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
            <DropdownMenuTrigger asChild>
                <div className="relative hover:text-black cursor-pointer">
                    <Bell className="size-4" />
                    {unreadCount > 0 && (
                        <span className="absolute -top-1.5 -right-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] text-white">
                            {unreadCount > 9 ? "+9" : unreadCount}
                        </span>
                    )}
                </div>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="bg-white text-black w-80 shadow-lg border-purple-100" align="end" sideOffset={10}>
                <div className="flex items-center justify-between px-4 py-2">
                    <DropdownMenuLabel className="text-sm text-gray-400 p-0">
                        {t('custom.notifications')}
                    </DropdownMenuLabel>
                    {unreadCount > 0 && (
                        <Button 
                            variant="ghost" 
                            size="sm" 
                            className="text-xs h-6 text-purple-600 hover:text-purple-700 hover:bg-purple-50"
                            onClick={() => {
                                // Optional: specific endpoint for marking all as read if available
                                // For now we can maybe loop or just leave it for individual items
                                // If there is an endpoint for read all, use it. User only gave /read with id.
                            }}
                        >
                            {/* {t('markAllAsRead')} */}
                        </Button>
                    )}
                </div>
                <DropdownMenuSeparator className="bg-gray-100 my-0" />
                <ScrollArea className="h-[400px]">
                    {notifications.length > 0 ? (
                        <ul className="py-1">
                            {notifications.map((notification) => (
                                <li key={notification.id}>
                                    <DropdownMenuItem 
                                        className={cn(
                                            "flex flex-col items-start gap-1 p-3 cursor-pointer focus:bg-gray-50",
                                            !notification.read_at ? "bg-purple-50/50" : "bg-white"
                                        )}
                                        onSelect={(e) => e.preventDefault()}
                                        onClick={(e) => handleMarkAsRead(e, notification.id)}
                                    >
                                        
                                        <div className="flex w-full justify-between items-start gap-2">
                                            <span className={cn("text-sm font-medium leading-none", !notification.read_at && "text-purple-900 font-bold")}>
                                                {notification.title || t('custom.notifications')}
                                            </span>
                                            {!notification.read_at && (
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="h-5 w-5 hover:bg-purple-200 rounded-full"
                                                    onClick={(e) => handleMarkAsRead(e, notification.id)}
                                                    title={t('custom.markAsRead')}
                                                >
                                                    <div className="h-1.5 w-1.5 rounded-full bg-purple-600" />
                                                </Button>
                                            )}
                                        </div>
                                        <p className="text-xs text-gray-500 line-clamp-2 leading-snug">
                                            {notification.body}
                                        </p>
                                        <span className="text-[10px] text-gray-400 mt-1">
                                            {formatDistanceToNow(new Date(notification.created_at), { 
                                                addSuffix: true,
                                                locale: locale === 'ar' ? ar : enUS 
                                            })}
                                        </span>
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator className="bg-gray-50 my-0" />
                                </li>
                            ))}
                        </ul>
                    ) : (
                        <div className="flex flex-col items-center justify-center h-40 text-gray-400 gap-2">
                            <Bell className="size-8 opacity-20" />
                            <span className="text-sm">{t('custom.noNotifications')}</span>
                        </div>
                    )}
                </ScrollArea>
            </DropdownMenuContent>
        </DropdownMenu>
    )
}