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

import { removeSnackbarAction, type SnackBarMessageType } from '@/modules/@common/notify/redux/slices';

import Alert from '@/mui/components/Alert/Alert';
import Collapse from '@/mui/components/Collapse/Collapse';

const TIMEOUT = 300;

type Props = {
  toast: SnackBarMessageType;
  forceClose: boolean;
};

function SnackbarItem({ toast, forceClose }: Props) {
  const [open, setOpen] = useState(true);
  const dispatch = useDispatch();

  const close = () => {
    setOpen(false);
    window.setTimeout(() => dispatch(removeSnackbarAction(toast.key)), TIMEOUT + 100);
  };

  const handleClose = () => {
    if (toast.onClose) {
      toast.onClose();
    }
    close();
  };

  useEffect(() => {
    if (toast.duration !== 0) {
      window.setTimeout(() => close(), toast.duration || 6000);
    }
  }, [toast.duration]);

  useEffect(() => {
    if (forceClose) {
      close();
    }
  }, [forceClose]);

  return (
    <Collapse in={open} timeout={TIMEOUT}>
      <Alert
        key={toast.key}
        severity={toast.variant}
        onClose={handleClose}
        variant="filled"
        style={{
          // eslint-disable-next-line local-rules/no-inline-styles
          width: 'fit-content',
          // eslint-disable-next-line local-rules/no-inline-styles
          minWidth: 280,
        }}
      >
        {toast.message}
      </Alert>
    </Collapse>
  );
}

export default SnackbarItem;
