import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import toastService from '@src/ToastService';
import { ErrorBoundary } from '@components/ErrorBoundary/index.jsx';
import { Toast } from '@components/Toast/index.jsx';

const ToastsItem = ({ toasts }) => {
  const [toastsArr, setToastsArr] = useState([]);

  useEffect(() => {
    setToastsArr(toasts);
  }, [toasts]);

  const deleteToastById = (id) => {
    setToastsArr(toastService.deleteToastById(id));
  };

  const toastsArray = useMemo(
    () =>
      toastsArr.map((t) => {
        const { id } = t;
        return <Toast key={id} {...t} deleteToastById={deleteToastById} />;
      }),
    [toastsArr],
  );

  return (
    <div>
      <ErrorBoundary>{toastsArray}</ErrorBoundary>
    </div>
  );
};

ToastsItem.propTypes = {
  toasts: PropTypes.array,
};

ToastsItem.defaultProps = {
  toasts: [],
};

export const Toasts = React.memo(ToastsItem);
