import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Refresh } from '@mui/icons-material';

import { JOB_STATE_CREATED, JOB_STATE_PROCESSING } from '@/modules/editorial/bulkActions/constants';

import { monitoringStateSelector } from '../../redux/selectors';
import { clearAction } from '../../redux/slices';
import { searchEventAction } from '@/modules/editorial/editorialSearch/reduxSearch/slices';

import { Alert, Button, Stack } from '@/mui/components';

import styles from './BulkActionsPanelSuccess.module.scss';

function BulkActionPanelSuccess() {
  const dispatch = useDispatch();
  const [shouldShow, setShouldShow] = useState(false);
  const monitoringState = useSelector(monitoringStateSelector);

  const handleRefresh = () => {
    setShouldShow(false);
    dispatch(searchEventAction());
    dispatch(clearAction());
  };

  useEffect(() => {
    if (
      monitoringState.length > 0 &&
      monitoringState.every((state) => ![JOB_STATE_PROCESSING, JOB_STATE_CREATED].includes(state.state))
    ) {
      setShouldShow(true);
    }
  }, [monitoringState]);

  if (!shouldShow) {
    return null;
  }

  return (
    <Stack className={styles.Root}>
      <Alert
        severity="success"
        variant="outlined"
        size="small"
        shape="square"
        action={
          <Button
            className={styles.RefreshBtn}
            variant="text"
            size="small"
            color="neutral"
            shape="rounded"
            startIcon={<Refresh />}
            onClick={handleRefresh}
          >
            Refresh
          </Button>
        }
      >
        Bulk actions completed. Please refresh the page to see the updated information
      </Alert>
    </Stack>
  );
}

export default BulkActionPanelSuccess;
