"use client"

import type { INotificationBellProps } from "./NotificationBell.d"
import type { JSX } from "react"

import { Bell } from "lucide-react"
import { FunctionComponent, useCallback, useRef, useState } from "react"

import { useAppSelector } from "@shared/hooks/useAppSelector"
import { Button } from "@shared/ui"

import { NotificationPopup } from "../NotificationPopup"

import styles from "./NotificationBell.module.scss"

export const NotificationBell: FunctionComponent<INotificationBellProps> =
	(): JSX.Element => {
		const unreadCount = useAppSelector(
			(state) => state.notifications.unreadCount,
		)
		const [isOpen, setIsOpen] = useState(false)
		const rootRef = useRef<HTMLDivElement>(null)

		const toggle = useCallback(() => setIsOpen((prev) => !prev), [])
		const close = useCallback(() => setIsOpen(false), [])

		return (
			<div className={styles.root} ref={rootRef}>
				<Button variant="icon" size="lg" onClick={toggle}>
					<Bell size={22} />
				</Button>
				{unreadCount > 0 && (
					<span className={styles.badge}>
						{unreadCount > 99 ? "99+" : unreadCount}
					</span>
				)}
				{isOpen && (
					<NotificationPopup
						onClose={close}
						anchorRef={rootRef}
					/>
				)}
			</div>
		)
	}
