"use client";

import { Bell, CheckCheck, Loader2 } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { useRouter } from "next/navigation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { NotificationItem } from "../type/notification.type";
import { useGetNotifications, useMarkNotificationAsRead, useUnreadCount } from "../hook/notification.hook";


function NotificationRow({ n }: { n: NotificationItem }) {
  const router = useRouter();
  const { mutate: markAsRead, isPending } = useMarkNotificationAsRead();
  const isUnread = n.status !== "READ";

  const openAction = () => {
    if (isUnread) markAsRead(n.id);
    if (!n.actionUrl) return;
    try {
      const url = new URL(n.actionUrl, window.location.origin);
      if (url.origin === window.location.origin) {
        router.push(url.pathname + url.search + url.hash);
      } else {
        window.location.href = url.href;
      }
    } catch {
      router.push(n.actionUrl);
    }
  };

  return (
    <button
      onClick={openAction}
      disabled={isPending}
      className={`w-full text-left px-4 py-3 border-b border-border last:border-0 hover:bg-muted/50 transition-colors flex items-start gap-2.5 ${
        isUnread ? "bg-primary/5" : ""
      }`}
    >
      {isUnread && (
        <span className="mt-1.5 h-1.5 w-1.5 rounded-full bg-primary shrink-0" />
      )}
      <div className={`min-w-0 flex-1 ${!isUnread ? "pl-4" : ""}`}>
        <p className="text-xs font-semibold text-foreground truncate">
          {n.title}
        </p>
        <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
          {n.message}
        </p>
        {n.actionUrl && n.actionLabel && (
          <span className="mt-1.5 inline-flex items-center rounded-md bg-primary px-2 py-0.5 text-[10px] font-semibold text-primary-foreground">
            {n.actionLabel}
          </span>
        )}
        <p className="text-[10px] text-muted-foreground/60 mt-1">
          {formatDistanceToNow(new Date(n.createdAt), { addSuffix: true })}
        </p>
      </div>
    </button>
  );
}

export function NotificationBell() {
  const { data: unreadCount = 0 } = useUnreadCount();
  const { data, isLoading } = useGetNotifications({ page: 1, limit: 10 });
  const notifications = data?.data ?? [];

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" className="relative h-9 w-9">
          <Bell className="h-4.5 w-4.5" />
          {unreadCount > 0 && (
            <span className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground">
              {unreadCount > 9 ? "9+" : unreadCount}
            </span>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-80 p-0">
        <div className="flex items-center justify-between px-4 py-3 border-b border-border">
          <p className="text-sm font-semibold text-foreground">
            Notifications
          </p>
          {unreadCount > 0 && (
            <span className="text-[10px] text-muted-foreground flex items-center gap-1">
              <CheckCheck className="h-3 w-3" />
              {unreadCount} unread
            </span>
          )}
        </div>

        <div className="max-h-80 overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
            </div>
          ) : notifications.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-10 gap-2">
              <Bell className="h-6 w-6 text-muted-foreground/30" />
              <p className="text-xs text-muted-foreground">
                No notifications yet
              </p>
            </div>
          ) : (
            notifications.map((n) => <NotificationRow key={n.id} n={n} />)
          )}
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}