"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Bell } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";
import { useT } from "@/i18n";
import { useMarkNotificationRead, useNotifications, useUnreadNotificationCount } from "@/features/notifications/use-notifications";
import { NotificationItem, NotificationsEmpty } from "@/features/notifications/notification-rows";
import type { AdminNotification } from "@/types/notification";

export const BELL_PREVIEW_ROWS = 5;

/**
 * The bell on the header: the unread badge the whole back office watches, a
 * dropdown preview of the newest items, and the deep link into the full inbox.
 * Only rendered where the inbox permission exists.
 */
export function NotificationBell() {
  const t = useT();
  const router = useRouter();
  const markRead = useMarkNotificationRead();

  const { data: unread = 0 } = useUnreadNotificationCount();
  const preview = useNotifications({ page: 1, rows: BELL_PREVIEW_ROWS });
  const items = preview.data?.Model ?? [];

  function openNotification(notification: AdminNotification) {
    if (!notification.is_read) {
      void markRead.mutate(notification.uuid);
    }
    if (notification.action_url) {
      void router.push(notification.action_url);
    } else {
      void router.push("/notifications");
    }
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          aria-label={t("notifications.bell")}
          className="relative inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
        >
          <Bell className="h-4.5 w-4.5" aria-hidden />
          {unread > 0 ? (
            <span
              aria-label={t("notifications.unread", { count: unread })}
              className="absolute end-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-semibold text-white"
            >
              {unread > 99 ? "99+" : unread}
            </span>
          ) : null}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-[22rem] p-1.5">
        <DropdownMenuLabel className="flex items-center justify-between px-2 py-1.5">
          <span className="text-sm font-semibold">{t("notifications.title")}</span>
          {unread > 0 ? (
            <span className="text-xs text-muted-foreground">
              {t("notifications.unread", { count: unread })}
            </span>
          ) : null}
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        <div className="max-h-80 space-y-0.5 overflow-y-auto">
          {preview.isPending && items.length === 0 ? (
            <BellSkeleton />
          ) : items.length === 0 ? (
            <NotificationsEmpty />
          ) : (
            items.map((notification) => (
              <NotificationItem
                key={notification.uuid}
                notification={notification}
                compact
                onOpen={() => openNotification(notification)}
              />
            ))
          )}
        </div>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href="/notifications" className="justify-center font-medium">
            {t("common.viewAll")}
          </Link>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

function BellSkeleton() {
  return (
    <div aria-busy="true" aria-label={bellLoading} className="space-y-2 p-2">
      {[0, 1, 2].map((row) => (
        <div key={row} className="flex items-center gap-3">
          <Skeleton className="h-8 w-8 shrink-0 rounded-full" />
          <Skeleton className="h-8 flex-1" />
        </div>
      ))}
    </div>
  );
}

const bellLoading = "Loading…";