import useOpenable from "@Front/Hooks/useOpenable";
import Toasts, { IToast } from "@Front/Stores/Toasts";
import { BellIcon } from "@heroicons/react/24/outline";
import React, { useEffect, useState } from "react";

import IconButton from "../../IconButton";
import classes from "./classes.module.scss";
import NotificationModal from "./NotificationModal";

export default function Notifications() {
	const [_toastList, setToastList] = useState<IToast[] | null>(Toasts.getInstance().toasts);
	const [hasNotifications, setHasNotifications] = useState<boolean>(Toasts.getInstance().toasts.length > 0);
	const { isOpen, close, toggle } = useOpenable();

	useEffect(() => {
		const handleToastChange = (newToastList: IToast[] | null) => {
			setToastList(newToastList);
			setHasNotifications(newToastList ? newToastList.length > 0 : false);
		};

		const removeOnToastChange = Toasts.getInstance().onChange(handleToastChange);

		return () => {
			removeOnToastChange();
		};
	}, []);

	return (
		<div className={classes["root"]}>
			{hasNotifications ? (
				<IconButton icon={<BellNotifIcon />} onClick={toggle} />
			) : (
				<IconButton icon={<BellIcon />} onClick={toggle} />
			)}

			<NotificationModal isOpen={isOpen} closeModal={close} />
		</div>
	);
}

function BellNotifIcon() {
	return (
		<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
			<path
				d="M14.8569 17.0817C16.7514 16.857 18.5783 16.4116 20.3111 15.7719C18.8743 14.177 17.9998 12.0656 17.9998 9.75V9.04919C17.9999 9.03281 18 9.01641 18 9C18 5.68629 15.3137 3 12 3C8.68629 3 6 5.68629 6 9L5.9998 9.75C5.9998 12.0656 5.12527 14.177 3.68848 15.7719C5.4214 16.4116 7.24843 16.857 9.14314 17.0818M14.8569 17.0817C13.92 17.1928 12.9666 17.25 11.9998 17.25C11.0332 17.25 10.0799 17.1929 9.14314 17.0818M14.8569 17.0817C14.9498 17.3711 15 17.6797 15 18C15 19.6569 13.6569 21 12 21C10.3431 21 9 19.6569 9 18C9 17.6797 9.05019 17.3712 9.14314 17.0818"
				stroke="#47535D"
				stroke-width="1.5"
				stroke-linecap="round"
				stroke-linejoin="round"
			/>
			<circle cx="17.5" cy="6.5" r="4.5" fill="#FF4617" />
		</svg>
	);
}
