import React, { useEffect, useState } from 'react';
import { faTimes } from '@fortawesome/free-solid-svg-icons/faTimes';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import isEqual from 'lodash/isEqual';
import { IToastProps } from '../Toast.interface';
import Style from './Toast.style';

const Toast: React.FunctionComponent<IToastProps> = React.memo(function Toast({ item, onDelete }: any) {
   const { id, message, opened, type, closeButton } = item;

   const [opening, setOpening] = useState(false);
   const [closing, setClosing] = useState(false);

   function RemoveToast(): void {
      setClosing(true);
      setOpening(false);
      setTimeout(() => {
         onDelete(id);
      }, 300);
   }

   useEffect(() => {
      if (opened) {
         setTimeout(() => {
            setOpening(true);
         }, 10);
      } else {
         RemoveToast();
      }
   }, [opened]);

   return (
      <Style>
         <div className={`ds-toast-container ${closing && 'closing'} ${opening && 'opening'} ${type}`}>
            <div className="ds-toast">
               <div className="message">{message}</div>
               {closeButton && (
                  <div className="close" onClick={RemoveToast}>
                     <FontAwesomeIcon icon={faTimes} />
                  </div>
               )}
            </div>
         </div>
      </Style>
   );
}, isEqual);

export default Toast;
