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

import LoggerFactory from 'services/logger/LoggerFactory';
import {killChannel} from 'services/channel.service';

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

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

import KillChannelForm from './kill-channel-form';
import {FormResponse} from 'components/modal/modal-form-response';

interface IKillChannelModal {
  isOpen: boolean;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  channelId: string;
  alias: string;
}

export const KillChannelModal = ({isOpen, setIsOpen, channelId, alias}: IKillChannelModal): React.JSX.Element => {
  const logger = LoggerFactory.getLogger('components/channel-icon-menu/kill-channel/KillChannelModal');
  const [formData, setFormData] = useState({
    reason: '',
    options: [] as string[],
    enteredAlias: ''
  });
  const [isFormValid, setIsFormValid] = useState(false);
  const [isFetching, setIsFetching] = useState(false);
  const [killResponse, setKillResponse] = useState<{error: string | boolean | Error; status: string | number; data?: any} | null>(null);
  const handleSubmit = async () => {
    if (!isFormValid) {
      return;
    }

    try {
      setIsFetching(true);

      const {reason, options} = formData;

      logger.info('Killing a channel [%s] with reason [%s]', channelId, reason);

      const response = await killChannel({
        channelId,
        reason,
        options,
        enteredAlias: formData.enteredAlias
      });

      logger.info('The channel [%s] was successfully killed', channelId);

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

      setIsFetching(false);

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

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

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

  return (
    <MultiStepModal
      isOpen={isOpen}
      closeModal={handleCloseModal}
      steps={[
        {
          title: 'Kill Channel',
          component: <KillChannelForm alias={alias} setIsValid={setIsFormValid} setFormData={setFormData} />,
          saveButton: {
            text: 'Kill Channel',
            className: 'testId-killChannel',
            disabled: !isFormValid || isFetching,
            onClick: handleSubmit
          }
        },
        {
          title: 'Kill Channel',
          component: <FormResponse response={killResponse || {error: '', status: '', data: null}} />,
          cancelDisabled: true,
          saveButton: {className: 'testId-doneButton'}
        }
      ]}
    />
  );
};

export default KillChannelModal;
