import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import * as snackbarSelectors from '../../../modules/@common/notify/redux/selectors';
import { SnackBarMessageType } from '@/modules/@common/notify/redux/slices';

import Stack from '../Stack/Stack';
import Snackbar from './Snackbar';
import SnackbarItem from './SnackbarItem';

type Props = {
  maxSnack: number;
};

function SnackbarGroup({ maxSnack }: Props) {
  const notifications = useSelector(snackbarSelectors.notifications) as SnackBarMessageType[];
  const [forceCloseElement, setForceCloseElement] = useState<string | undefined>(undefined);
  const [firstToast] = notifications;

  const notificationsToShow = notifications.slice(0, maxSnack).reverse();

  useEffect(() => {
    if (notifications.length > maxSnack) {
      const key = notificationsToShow[notificationsToShow.length - 1]?.key;

      if (key) {
        setForceCloseElement(key);
      }
    }
  }, [notifications.length]);

  return (
    <Snackbar
      open={!!firstToast}
      autoHideDuration={null}
      transitionDuration={0}
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'left',
      }}
      style={{
        // eslint-disable-next-line local-rules/no-inline-styles
        marginTop: 'env(safe-area-inset-top)',
        // eslint-disable-next-line local-rules/no-inline-styles
        marginBottom: 'env(safe-area-inset-bottom)',
      }}
    >
      <Stack spacing={2} flexDirection="column">
        {notificationsToShow.map((toast) => (
          <SnackbarItem toast={toast} key={toast.key} forceClose={forceCloseElement === toast.key} />
        ))}
      </Stack>
    </Snackbar>
  );
}

export default SnackbarGroup;
