"use client";

import { Bell } from "lucide-react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { NotificationItem } from "@/app/(dashboard)/notifications/notification.types";
import { useMarkAllAsRead } from "@/app/(dashboard)/notifications/hooks/useMarkAllAsRead";
import { useMarkAsRead } from "@/app/(dashboard)/notifications/hooks/useMarkAsRead";
import { useNotifications } from "@/app/(dashboard)/notifications/hooks/useNotifications";
import { useUnreadCount } from "@/app/(dashboard)/notifications/hooks/useUnreadCount";
import { EmptyNotification } from "./EmptyNotification";
import { NotificationList } from "./NotificationList";
import { NotificationSkeleton } from "./NotificationSkeleton";

type NotificationTab = "all" | "unread";

export default function Notifications() {
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState<NotificationTab>("all");
  const router = useRouter();
  const { data, isLoading } = useNotifications({
    page: 1,
    per_page: 10,
    unread_only: tab === "unread",
  });
  const { data: unreadData } = useUnreadCount();
  const { mutateAsync: markAsRead } = useMarkAsRead();
  const { mutate: markAllAsRead, isPending: isMarkingAll } = useMarkAllAsRead();
  const notifications = data?.data.notifications.data ?? [];
  const unreadCount = unreadData?.data.unread_count ?? 0;
  const badge = unreadCount > 99 ? "99+" : String(unreadCount);

  const handleNotification = async (notification: NotificationItem) => {
    if (!notification.is_read) await markAsRead(notification.id);
    setOpen(false);
    router.push(`/notifications/${notification.id}`);
  };

  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger asChild>
        <button
          className={`${open ? "bg-primary-button text-white" : "bg-white dark:bg-zinc-900"} border-border relative flex h-14 w-14 items-center justify-center rounded-full border bg-gray-100 hover:bg-gray-200 focus:outline-none dark:bg-zinc-800`}
        >
          <Bell size={20} />
          {unreadCount > 0 && (
            <span className="absolute top-0 right-0 flex min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] leading-4 text-white">
              {badge}
            </span>
          )}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="end"
        className="border-border w-[380px] rounded-2xl p-0"
      >
        <div className="border-border flex items-center justify-between border-b p-4">
          <h3 className="text-lg font-bold">Notifications</h3>
          <button
            type="button"
            disabled={isMarkingAll || unreadCount === 0}
            onClick={() => markAllAsRead()}
            className="border-border cursor-pointer rounded-lg border px-2 py-1 text-sm font-medium text-blue-600 hover:scale-102 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {isMarkingAll ? "Marking..." : "Mark all as read"}
          </button>
        </div>
        <div className="flex gap-2 px-4 py-3">
          <button
            type="button"
            onClick={() => setTab("all")}
            className={`rounded-full px-4 py-1 text-sm ${tab === "all" ? "bg-blue-100 font-medium text-blue-600" : "hover:bg-gray-100"}`}
          >
            All
          </button>
          <button
            type="button"
            onClick={() => setTab("unread")}
            className={`rounded-full px-4 py-1 text-sm ${tab === "unread" ? "bg-blue-100 font-medium text-blue-600" : "hover:bg-gray-100"}`}
          >
            Unread
          </button>
        </div>
        <div className="max-h-[500px] overflow-y-auto">
          {isLoading ? (
            <NotificationSkeleton />
          ) : notifications.length ? (
            <NotificationList
              notifications={notifications}
              onSelect={handleNotification}
            />
          ) : (
            <EmptyNotification />
          )}
        </div>
        <div className="flex w-full justify-end p-3">
          <button
            type="button"
            onClick={() => {
              setOpen(false);
              router.push("/notifications");
            }}
            className="border-border w-full cursor-pointer rounded-lg border py-2 text-sm font-medium hover:bg-gray-100 dark:hover:bg-zinc-800"
          >
            See all notifications
          </button>
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
