/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React, {ChangeEvent, useState} from 'react';
import {faQuestionCircle} from '@fortawesome/free-solid-svg-icons';

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

import {transformToPortalError} from 'utility/error-handler';
import {createChannelErrorMessages} from 'constants/error-messages';
import {documentationLinks} from 'constants/links';

import {LoadingWheel} from 'components/loaders';
import Input from 'components/forms/Input';
import {NewTabLink} from 'components/new-tab-link';
import {Label} from 'components/label';
import {DialogForm, Error, FormLoaderContainer} from 'components/modal/modal-form-response/style';
import {Modal} from 'components/modal';

interface ICreateChannelInput {
  setCreateChannelModalOpened: React.Dispatch<React.SetStateAction<boolean>>;
  getChannelList: () => Promise<void>;
}

const CreateChannelModal = ({setCreateChannelModalOpened, getChannelList}: ICreateChannelInput): React.JSX.Element => {
  const logger = LoggerFactory.getLogger('view/channels/create-channel/CreateChannelModal');
  const initialState = {
    alias: '',
    name: '',
    description: ''
  };
  const [inputValues, setInputValue] = useState(initialState);
  const {alias, name, description} = inputValues;
  const [isFormValid, setIsFormValid] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
    const {name, value} = event.target;

    setInputValue({
      ...inputValues,
      [name]: value
    });
  };

  const handleClose = (): void => {
    setCreateChannelModalOpened(false);
  };

  const handleSubmit = async (): Promise<void> => {
    const valid = alias.trim() && name.trim() && description.trim();

    if (!valid) {
      setIsFormValid(false);

      return;
    }

    setIsLoading(true);

    try {
      logger.info('Creating a channel with the following parameters : [%j]', {
        alias,
        name,
        description
      });

      await createChannel({alias, name, description});

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

      setInputValue(initialState);
      setIsLoading(false);

      await getChannelList();

      handleClose();
    } catch (e) {
      const {status, message, requestPayload} = transformToPortalError(e);

      setIsLoading(false);
      const errorMessage = (createChannelErrorMessages as Record<string, string>)[status] || message || createChannelErrorMessages['default'];
      setError(errorMessage);

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

  return (
    <Modal
      close={handleClose}
      submitButton={{
        className: 'testId-createChannel',
        disabled: isLoading,
        onClick: handleSubmit,
        label: 'Create Channel'
      }}
      cancelButton={{onClick: handleClose}}>
      {isLoading ? (
        <FormLoaderContainer>
          <LoadingWheel color="dark" />
        </FormLoaderContainer>
      ) : (
        <DialogForm>
          <h3 className="testId-createChannelForm">
            Create Channel <NewTabLink link={documentationLinks.createChannel} icon={faQuestionCircle} iconColor="black" />
          </h3>
          <Label htmlFor="alias" text="Alias" />
          <Input onChange={handleChange} value={alias} name="alias" placeholder={'Alias'} error={!isFormValid && !alias} />
          {!isFormValid && !alias && <Error className="error-message testId-displayMessage">Alias can not be empty</Error>}
          <Label htmlFor="name" text="Name" />
          <Input onChange={handleChange} value={name} name="name" placeholder={'Name'} error={!isFormValid && !name} />
          {!isFormValid && !name && <Error className="error-message testId-displayMessage">Name can not be empty</Error>}
          <Label htmlFor="description" text="Description" />
          <Input onChange={handleChange} value={description} name="description" placeholder={'Description'} error={!isFormValid && !description} />
          {!isFormValid && !description && <Error className="error-message testId-displayMessage">Description can not be empty</Error>}
          {error && <Error className="error-message testId-displayMessage">{error}</Error>}
        </DialogForm>
      )}
    </Modal>
  );
};

export default CreateChannelModal;
