import React, { useEffect, useMemo } from "react";
import reactDom from "react-dom";
import classNames from "classnames";
import Notification from "./Notification";
import { useUINotifications } from "ui/controller/uiNotificationsViewModel";
import { useUIStore } from "ui/data/uiSlice";
import NotificationI from "ui/domain/uiNotificationEntity";

const NotificationsField = () => {
  const store = useUIStore();
  const { notifications, remove } = useUINotifications(store);

  let notificationsRendedField = useMemo(() => {
    return document.createElement("div");
  }, []);

  useEffect(() => {
    document.body.appendChild(notificationsRendedField);
    return () => {
      document.body.removeChild(notificationsRendedField);
    };
  }, [notificationsRendedField]);

  const closeHandler = (uid: NotificationI["uid"]) => {
    remove(uid);
  };

  return reactDom.createPortal(
    <div
      className={classNames("none fixed bottom-5 right-5 z-50 w-96", {
        "block!": notifications.length,
      })}
    >
      {
        // eslint-disable-next-line array-callback-return
        notifications.map((notification) => {
          if (notification.delay && notification.uid + (notification.delay ?? 0) < Date.now())
            return null;
          return (
            <Notification
              key={notification.uid}
              onClose={() => closeHandler(notification.uid)}
              title={notification.title}
              type={notification.status}
              delay={notification.delay}
            >
              {notification.body}
            </Notification>
          );
        })
      }
    </div>,
    notificationsRendedField,
    "popupNoti"
  );
};

export default NotificationsField;
