import React, { createRef, useEffect, useRef, useCallback } from 'react';
import { dismiss } from 'helpers/animationHelpers';
import Message from './Message';
import './Notification.css';

const Notifications = props => {
  const { noIcons, noTime, time, notifications, removeNotification, ...rest } = props;
  const targets = useRef([]);

  const removeMessage = useCallback(i => {
    if (removeNotification) removeNotification(i);
  }, [ removeNotification ]);

  useEffect(() => {
    if (!noTime && notifications?.length >= 1) {
      const timer = setTimeout(() => {
        dismiss({
          targets: [ targets.current[0] ],
          onClose: () => removeMessage(0),
        });
        clearTimeout(timer);
      }, time || 4000);

      return () => clearTimeout(timer);
    }

  }, [ notifications, time, noTime, removeMessage ]);

  const buildNotifications = () => {
    const refs = notifications?.map((msg, i) => (
      targets.current[i] ?? createRef()
    ));

    targets.current = [ ...refs ];


    return notifications?.map((msg, i) => {
      const args = {
        targets: [ targets.current[i] ],
        onClose: () => removeMessage(i),
      };

      return (
        <Message
          key={i}
          ref={targets.current[i]}
          message={msg}
          noIcons={noIcons}
          args={args}
          {...rest}
        />
      );
    });
  };

  return (
    <div className="notifications">
      {buildNotifications()}
    </div>
  );
};

export { Notifications };