/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React, {useState} from 'react';
import {useDispatch} from 'react-redux';

import LoggerFactory from 'services/logger/LoggerFactory';
import {deleteChannel} from 'services/channel.service';
import {listChannels} from 'store/action/channels';

import {transformToPortalError} from 'utility/error-handler';
import {deleteChannelErrorMessages} from 'constants/error-messages';

import {MultiStepModal} from 'components/modal/multi-step-modal';

import DeleteChannelForm from './delete-channel-form';
import {FormResponse} from 'components/modal/modal-form-response';

interface IDeleteChannelModal {
  isOpen: boolean;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  channelId: string;
  alias: string;
  redirect?: () => void;
}

export const DeleteChannelModal = ({isOpen, setIsOpen, channelId, alias, redirect}: IDeleteChannelModal): React.JSX.Element => {
  const logger = LoggerFactory.getLogger('components/channel-icon-menu/delete-channel/DeleteChannelModal');
  const dispatch = useDispatch();
  const [isFormValid, setIsFormValid] = useState(false);
  const [isFetching, setIsFetching] = useState(false);
  const [deleteChannelResponse, setDeleteChannelResponse] = useState<{error: string | boolean | Error; status: string | number; data?: any} | null>(null);
  const handleSubmit = async () => {
    if (!isFormValid) {
      return;
    }

    try {
      setIsFetching(true);

      logger.info('Deleting a channel [%s][%s]', alias, channelId);

      const response = await deleteChannel({channelId, alias});

      logger.info('Channel [%s][%s] was successfully deleted', alias, channelId);

      setDeleteChannelResponse({status: 'ok', error: false, data: response});
      setIsFetching(false);
    } catch (e) {
      const {status, message, requestPayload, statusCode} = transformToPortalError(e);

      setIsFetching(false);

      const errorMessage = (deleteChannelErrorMessages as Record<string, string>)[status] || message || deleteChannelErrorMessages['default'];
      setDeleteChannelResponse({
        status: statusCode || 'error',
        error: errorMessage
      });

      logger.error(`${errorMessage} [%s]`, status, requestPayload);
    }
  };

  const handleCloseModal = (): void => {
    setIsOpen(false);
  };

  const onDeleteSuccess = async (): Promise<void> => {
    setIsOpen(false);

    logger.info('Updating the list of channels after the [%s][%s] channel was deleted', alias, channelId);

    await dispatch(listChannels() as any);

    logger.info('The list of channels was updated successfully');

    if (redirect) {
      redirect();
    }
  };

  return (
    <MultiStepModal
      isOpen={isOpen}
      closeModal={deleteChannelResponse?.status === 'ok' ? onDeleteSuccess : handleCloseModal}
      steps={[
        {
          title: 'Delete Channel',
          component: <DeleteChannelForm alias={alias} setIsValid={setIsFormValid} />,
          saveButton: {
            text: 'Delete Channel',
            className: 'testId-deleteChannel',
            disabled: !isFormValid || isFetching,
            onClick: handleSubmit
          }
        },
        {
          title: 'Delete Channel',
          component: <FormResponse response={deleteChannelResponse || {error: '', status: '', data: null}} />,
          cancelDisabled: true,
          saveButton: {
            className: 'testId-doneButton',
            onClick: onDeleteSuccess
          }
        }
      ]}
    />
  );
};

export default DeleteChannelModal;
