"use client";

import { useState } from "react";
import { Bell } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useNotificationsFeed } from "@/lib/hooks/use-notifications-feed";
import type { CafeNotification } from "@/lib/api/notifications";
import { numberLocaleForUi } from "@/lib/format-datetime";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { NotificationDetailPanel, NotificationRow } from "@/components/notifications/notification-ui";
import { cn } from "@/lib/utils";

export function NotificationCenter() {
  const t = useTranslations("notifications");
  const locale = useLocale();
  const numberLocale = numberLocaleForUi(locale);
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState<CafeNotification | null>(null);

  const { items, unreadCount, openNotification, markAllRead } = useNotificationsFeed({
    enableToasts: true,
    limit: 20,
  });

  const handleSelect = async (n: CafeNotification) => {
    await openNotification(n);
    setSelected({ ...n, isRead: true });
  };

  const handleOpenChange = (next: boolean) => {
    setOpen(next);
    if (!next) setSelected(null);
  };

  const isRtl = locale !== "en";

  return (
    <DropdownMenu open={open} onOpenChange={handleOpenChange}>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="icon"
          className="relative shrink-0"
          aria-label={t("title")}
        >
          <Bell className="size-4" />
          {unreadCount > 0 ? (
            <span className="absolute -top-1 -end-1 flex size-5 items-center justify-center rounded-full bg-[#0F6E56] text-[10px] font-bold text-white">
              {unreadCount > 9
                ? locale === "fa"
                  ? "۹+"
                  : "9+"
                : unreadCount.toLocaleString(numberLocale)}
            </span>
          ) : null}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align={isRtl ? "start" : "end"}
        sideOffset={4}
        collisionPadding={12}
        className={cn(
          "w-80 max-h-[min(24rem,70vh)] overflow-y-auto overflow-x-hidden p-0",
          "rounded-xl border border-border/80 shadow-lg"
        )}
        onCloseAutoFocus={(e) => e.preventDefault()}
      >
        <div className="sticky top-0 z-10 flex items-center justify-between border-b border-border/80 bg-card px-3 py-2">
          <span className="text-sm font-semibold">{t("title")}</span>
          {unreadCount > 0 && !selected ? (
            <button
              type="button"
              className="text-xs font-medium text-[#0F6E56] hover:underline"
              onClick={() => void markAllRead()}
            >
              {t("markAllRead")}
            </button>
          ) : null}
        </div>

        {selected ? (
          <NotificationDetailPanel
            item={selected}
            locale={locale}
            onBack={() => setSelected(null)}
          />
        ) : items.length === 0 ? (
          <p className="px-3 py-8 text-center text-sm text-muted-foreground">{t("empty")}</p>
        ) : (
          <ul className="flex flex-col gap-2 p-2">
            {items.map((n) => (
              <li key={n.id}>
                <NotificationRow
                  item={n}
                  locale={locale}
                  compact
                  onSelect={(item) => void handleSelect(item)}
                />
              </li>
            ))}
          </ul>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
