import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useNotifications } from "../context/NotificationsContext";
import { BellIcon } from "./icons";
import { relativeTime } from "../utils";

export function NotificationBell() {
	const { items, unreadCount, markRead, markAllRead, clear } = useNotifications();
	const [open, setOpen] = useState(false);
	const ref = useRef<HTMLDivElement>(null);
	const navigate = useNavigate();

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

	return (
		<div className="relative" ref={ref}>
			<button
				onClick={() => setOpen((o) => !o)}
				className="relative flex h-10 w-10 items-center justify-center rounded-lg text-muted transition hover:bg-surface-raised hover:text-text"
				aria-label="Notifications"
			>
				<BellIcon className="h-5 w-5" />
				{unreadCount > 0 && (
					<span className="absolute right-1 top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-rejected px-1 text-[10px] font-bold text-white">
						{unreadCount > 99 ? "99+" : unreadCount}
					</span>
				)}
			</button>

			{open && (
				<div className="animate-fade-in absolute right-0 z-40 mt-2 w-80 rounded-xl border border-border-strong bg-surface shadow-2xl">
					<div className="flex items-center justify-between border-b border-border px-4 py-2.5">
						<span className="text-sm font-semibold">Notifications</span>
						<div className="flex gap-2 text-xs">
							<button className="text-muted hover:text-text" onClick={() => markAllRead()}>
								Mark all read
							</button>
							<button className="text-muted hover:text-rejected" onClick={() => clear()}>
								Clear
							</button>
						</div>
					</div>
					<div className="max-h-96 overflow-y-auto">
						{items.length === 0 && (
							<p className="px-4 py-8 text-center text-sm text-muted">No notifications yet</p>
						)}
						{items.map((n) => (
							<button
								key={n.id}
								onClick={() => {
									markRead(n.id);
									setOpen(false);
									if (n.request_id) navigate(`/requests/${n.request_id}`);
								}}
								className={`flex w-full flex-col items-start gap-0.5 border-b border-border/60 px-4 py-3 text-left transition hover:bg-surface-raised ${
									n.read ? "opacity-60" : ""
								}`}
							>
								<div className="flex w-full items-center gap-2">
									{!n.read && <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />}
									<span className="text-sm font-medium text-text">{n.title}</span>
								</div>
								<span className="text-xs text-muted">{n.message}</span>
								<span className="text-[11px] text-faint">{relativeTime(n.created_at)}</span>
							</button>
						))}
					</div>
				</div>
			)}
		</div>
	);
}
