"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import {
  NotificationDropdown,
  type NotificationItem,
} from "@/components/notifications/notification-dropdown";

export function NotificationBell() {
  const [open, setOpen] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const [items, setItems] = useState<NotificationItem[]>([]);
  const ref = useRef<HTMLDivElement>(null);

  const load = useCallback(async () => {
    const [countRes, listRes] = await Promise.all([
      fetch("/api/notifications/unread-count"),
      fetch("/api/notifications?limit=10&page=1"),
    ]);
    if (countRes.ok) {
      const json = await countRes.json();
      setUnreadCount(json.count ?? 0);
    }
    if (listRes.ok) {
      const json = await listRes.json();
      setItems(json.data ?? []);
    }
  }, []);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void load();
    }, 0);
    const interval = window.setInterval(() => void load(), 60_000);
    return () => {
      window.clearTimeout(timeout);
      window.clearInterval(interval);
    };
  }, [load]);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, [open]);

  async function markRead(id: string) {
    await fetch(`/api/notifications/${id}/read`, { method: "PATCH" });
    await load();
  }

  async function markAllRead() {
    await fetch("/api/notifications/read-all", { method: "POST" });
    await load();
  }

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => {
          setOpen((v) => !v);
          if (!open) void load();
        }}
        className="relative rounded-md border border-neutral-300 p-2 text-neutral-700 hover:bg-neutral-50"
        aria-label="الإشعارات"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          className="h-5 w-5"
          aria-hidden
        >
          <path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
          <path d="M13.73 21a2 2 0 01-3.46 0" />
        </svg>
        {unreadCount > 0 ? (
          <span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-red-600 px-1 text-[10px] font-bold text-white">
            {unreadCount > 99 ? "99+" : unreadCount}
          </span>
        ) : null}
      </button>
      {open ? (
        <NotificationDropdown
          items={items}
          unreadCount={unreadCount}
          onMarkRead={(id) => void markRead(id)}
          onMarkAllRead={() => void markAllRead()}
          onClose={() => setOpen(false)}
        />
      ) : null}
    </div>
  );
}
