import React from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';

import {
  BULK_ACTIONS_ADD_TAGS,
  BULK_ACTIONS_ARCHIVE,
  BULK_ACTIONS_REPLACE_SITES,
  BULK_ACTIONS_REPLACE_TAGS,
  BULK_ACTIONS_SHARE_ACCESS_LEVEL,
  BULK_ACTIONS_SHARE_WITH_USERS,
  JOB_STATE_CREATED,
  JOB_STATE_ERROR,
  JOB_STATE_PROCESSING,
  JOB_STATE_READY,
} from '@/modules/editorial/bulkActions/constants';

import { monitoringIdsSelector, monitoringStateSelector } from '@/modules/editorial/bulkActions/redux/selectors';
import { setAction } from '@/modules/editorial/bulkActions/redux/slices';

import Container from '@/modules/layout/components/FloatBlock/components/Container/Container';
import Completed from './components/Completed/Completed';
import Processing from './components/Processing/Processing';

const GET_TITLE_BY_TYPE = {
  [BULK_ACTIONS_ARCHIVE]: 'Archiving Videos',
  [BULK_ACTIONS_ADD_TAGS]: 'Adding Tags',
  [BULK_ACTIONS_REPLACE_TAGS]: 'Replacing Tags',
  [BULK_ACTIONS_REPLACE_SITES]: 'Replacing Hubs',
  [BULK_ACTIONS_SHARE_WITH_USERS]: 'Sharing with users',
  [BULK_ACTIONS_SHARE_ACCESS_LEVEL]: 'Changing access level',
};

function parseMessage(input = '') {
  const defaultStatus = {
    progress: 0,
    total: 0,
    completed: 0,
    skipped: 0,
  };

  try {
    const parsedStatus = JSON.parse(input);
    return { ...defaultStatus, ...parsedStatus };
  } catch (e) {
    console.error('Invalid JSON input:', e);
    return defaultStatus;
  }
}

function BulkActionStatusDialog(props) {
  const dispatch = useDispatch();
  const monitoringIds = useSelector(monitoringIdsSelector);
  const monitoringState = useSelector(monitoringStateSelector);

  const monitoringStateOrderedByIds = [...monitoringIds]
    .reverse()
    .map((monitoringId) => monitoringState.find((state) => state.entityId === monitoringId))
    .filter(Boolean);

  const handleClose = (monitoringId) => {
    const updatedMonitoringIds = monitoringIds.filter((id) => id !== monitoringId);
    const updatedMonitoringState = monitoringState.filter((state) => state.entityId !== monitoringId);

    dispatch(
      setAction({
        monitoringIds: updatedMonitoringIds,
        monitoringState: updatedMonitoringState,
      }),
    );
  };

  return (
    <>
      {monitoringStateOrderedByIds.map((state, index) => {
        const stateInfo = parseMessage(state.message);
        return (
          <Container
            headerWithoutRadius={props.headerWithoutRadius || index > 0}
            key={state.entityId}
            title={GET_TITLE_BY_TYPE[state.type]}
            onClose={() => handleClose(state.entityId)}
          >
            {[JOB_STATE_PROCESSING, JOB_STATE_CREATED].includes(state.state) && (
              <Processing progress={stateInfo.progress} total={stateInfo.total} />
            )}
            {state.state === JOB_STATE_READY && (
              <Completed completed={stateInfo.completed} skipped={stateInfo.skipped} />
            )}
            {state.state === JOB_STATE_ERROR && <span>Error</span>}
          </Container>
        );
      })}
    </>
  );
}

BulkActionStatusDialog.propTypes = {
  headerWithoutRadius: PropTypes.bool,
};

export default BulkActionStatusDialog;
