import React, { useEffect, useState } from 'react';
import { Event } from '../../services/event.service';
import Style from './toast-list.style';
import Toast, { IItemsToast } from './toast/toast';

const ToastObs = new Event<IItemsToast>();
let id = 0;

export const ToastList: React.FunctionComponent<any> & { show: any } = () => {
   const [items, setItems] = useState<any[]>([] as any);

   useEffect(() => {
      const obs = ToastObs.observable.subscribe((value) => {
         id += 1;
         const index = id;

         value.forceClose = () => {
            clearTimeout(value.closeTimer);

            setTimeout(() => {
               setItems((newItems: any) => {
                  const list = [...newItems];
                  return list.map((i) => (i.id != index ? i : { ...i, opened: false }));
               });

               setTimeout(() => {
                  setItems((newItems: any) => {
                     const list = [...newItems];
                     return list.filter((i) => i.id != index);
                  });
               }, 25);
            }, 50);
         };

         value.closeTimer = () => {
            setTimeout(() => {
               setItems((newItems: any) => {
                  const list = [...newItems];
                  return list.map((i) => (i.id != index ? i : { ...i, opened: false }));
               });

               setTimeout(() => {
                  setItems((newItems: any) => {
                     const list = [...newItems];
                     return list.filter((i) => i.id != index);
                  });
               }, 300);
            }, 3000);
         };

         setItems((newItems: any) => {
            const list = [...newItems];

            list.push({ ...value, opened: true, id: index });
            return list;
         });

         value.closeTimer();
      });

      return () => obs.unsubscribe();
   }, []);

   return (
      <Style>
         {items.map((item) => (
            <Toast key={`toast-${item.id}`} item={item} />
         ))}
      </Style>
   );
};

ToastList.show = (options: IItemsToast) => {
   ToastObs.set(options);
};
