"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";

type Notification = {
  id: string;
  message: string;
  link: string | null;
  read: boolean;
  createdAt: string;
};

export default function AdminToastNotifier() {
  const [toasts, setToasts] = useState<Notification[]>([]);
  const seenIds = useRef<Set<string> | null>(null);
  const router = useRouter();

  async function poll() {
    const res = await fetch("/api/notifications");
    const data = await res.json();
    const current: Notification[] = data.notifications || [];

    if (seenIds.current === null) {
      // First load — just record what's already there, nothing to pop up
      // for yet (otherwise every existing unread notification would flash
      // on every page load).
      seenIds.current = new Set(current.map((n) => n.id));
      return;
    }

    const fresh = current.filter((n) => !seenIds.current!.has(n.id));
    if (fresh.length > 0) {
      setToasts((prev) => [...fresh, ...prev].slice(0, 3));
      for (const n of fresh) seenIds.current!.add(n.id);
      fresh.forEach((n) => {
        setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== n.id)), 8000);
      });
    }
  }

  useEffect(() => {
    poll();
    const interval = setInterval(poll, 20000);
    return () => clearInterval(interval);
  }, []);

  function dismiss(id: string) {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }

  function open(n: Notification) {
    dismiss(n.id);
    if (n.link) router.push(n.link);
  }

  if (toasts.length === 0) return null;

  return (
    <div className="fixed top-4 right-4 z-[100] space-y-2 w-80 max-w-[calc(100vw-2rem)]">
      {toasts.map((n) => (
        <div
          key={n.id}
          onClick={() => open(n)}
          className="bg-neutral-900 border border-red-800/60 rounded-lg shadow-xl p-4 cursor-pointer animate-[fadeInUp_0.3s_ease-out_both] hover:border-red-600"
        >
          <div className="flex items-start justify-between gap-2">
            <p className="text-sm text-neutral-100 flex-1">{n.message}</p>
            <button
              onClick={(e) => {
                e.stopPropagation();
                dismiss(n.id);
              }}
              className="text-neutral-500 hover:text-white shrink-0 text-xs"
            >
              ✕
            </button>
          </div>
          <p className="text-xs text-red-500 mt-1.5">Click to view →</p>
        </div>
      ))}
    </div>
  );
}
