"use client";

import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, useCallback } from "react";
import Link from "next/link";
import { Bell } from "lucide-react";
import { useToken } from "@/lib/auth/useToken";
import { notificationsApi } from "@/lib/api/notifications";
import type { ApiNotification } from "@/lib/api/types";
import { formatDateTime } from "@/lib/utils";

const POLL_MS = 60_000;

export default function NotificationBell() {
  const router = useRouter();
  const { token, ready } = useToken();
  const [open, setOpen] = useState(false);
  const [count, setCount] = useState(0);
  const [items, setItems] = useState<ApiNotification[]>([]);
  const [loading, setLoading] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  const loadCount = useCallback(async () => {
    if (!token) return;
    try {
      const r = await notificationsApi.unreadCount(token);
      setCount(r.count ?? 0);
    } catch {
      /* noop */
    }
  }, [token]);

  const loadList = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const r = await notificationsApi.list(token, { perPage: 8 });
      setItems(r.data);
      setCount(r.unread_count);
    } finally {
      setLoading(false);
    }
  }, [token]);

  useEffect(() => {
    if (!ready || !token) return;
    loadCount();
    const id = window.setInterval(loadCount, POLL_MS);
    return () => window.clearInterval(id);
  }, [ready, token, loadCount]);

  useEffect(() => {
    if (!open) return;
    loadList();
  }, [open, loadList]);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [open]);

  const markAll = async () => {
    if (!token) return;
    await notificationsApi.markAllRead(token);
    setCount(0);
    setItems((prev) => prev.map((n) => ({ ...n, is_read: true })));
  };

  const handleClick = async (n: ApiNotification) => {
    if (!token) return;
    if (!n.is_read) {
      try {
        await notificationsApi.markRead(token, n.id);
      } catch {
        /* noop */
      }
      setItems((prev) => prev.map((p) => (p.id === n.id ? { ...p, is_read: true } : p)));
      setCount((c) => Math.max(0, c - 1));
    }
    // Open the RFQ / order the notification is about (B33).
    if (n.link) {
      setOpen(false);
      router.push(n.link);
    }
  };

  return (
    <div ref={wrapRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="relative inline-flex h-10 w-10 items-center justify-center rounded-lg text-gray-600 hover:bg-gray-100"
        aria-label="Notifications"
      >
        <Bell className="h-5 w-5" />
        {count > 0 && (
          <span className="absolute -right-0.5 -top-0.5 inline-flex min-w-[18px] items-center justify-center rounded-full bg-[#CC1414] px-1 text-[10px] font-semibold text-white">
            {count > 99 ? "99+" : count}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 z-50 mt-2 w-[calc(100vw-2rem)] max-w-sm overflow-hidden rounded-xl bg-white shadow-lg ring-1 ring-gray-200 sm:w-80">
          <div className="flex items-center justify-between border-b border-gray-100 px-4 py-2">
            <h3 className="text-sm font-semibold text-gray-900">Notifications</h3>
            {count > 0 && (
              <button onClick={markAll} className="text-xs font-medium text-[#CC1414] hover:underline">
                Mark all read
              </button>
            )}
          </div>
          <div className="max-h-96 overflow-y-auto">
            {loading ? (
              <div className="p-4 text-center text-sm text-gray-500">Loading…</div>
            ) : items.length === 0 ? (
              <div className="p-6 text-center text-sm text-gray-500">No notifications.</div>
            ) : (
              <ul className="divide-y divide-gray-100">
                {items.map((n) => (
                  <li key={n.id}>
                    <button
                      onClick={() => handleClick(n)}
                      className={`flex w-full flex-col gap-1 px-4 py-3 text-left hover:bg-gray-50 ${!n.is_read ? "bg-[#CC1414]/5" : ""}`}
                    >
                      <span className="text-sm font-medium text-gray-900">{n.title ?? "Notification"}</span>
                      {n.body && <span className="text-xs text-gray-600 line-clamp-2">{n.body}</span>}
                      {n.created_at && (
                        <span className="text-[10px] uppercase tracking-wide text-gray-400">
                          {formatDateTime(n.created_at)}
                        </span>
                      )}
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
          <div className="border-t border-gray-100 bg-gray-50 px-4 py-2 text-center">
            <Link
              href="/notifications"
              onClick={() => setOpen(false)}
              className="text-xs font-medium text-[#CC1414] hover:underline"
            >
              View all
            </Link>
          </div>
        </div>
      )}
    </div>
  );
}
