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

import {ConfirmButton} from 'components/buttons';
import {theme} from 'components/shared/theme';

import {ModalOverlay, ModalContainer, ModalButtonsContaier, CloseButton} from './style';

interface IModal {
  children: React.JSX.Element;
  close: () => void;
  className?: string;
  submitButton?: {
    onClick: () => void;
    label?: string;
    className?: string;
    disabled?: boolean;
    textColor?: string;
    backgroundColor?: string;
    borderColor?: string;
  };
  cancelButton?: {
    onClick?: () => void;
    label?: string;
    className?: string;
    disabled?: boolean;
    textColor?: string;
    backgroundColor?: string;
    borderColor?: string;
  };
}

const Modal = (props: IModal): React.JSX.Element => {
  const {children, className, close} = props;
  const submitButton = {
    onClick: props.submitButton?.onClick || null,
    label: 'Submit',
    disabled: false,
    textColor: theme.colors.gray700,
    backgroundColor: theme.colors.white,
    borderColor: theme.colors.gray700,
    ...props.submitButton
  };
  const cancelButton = {
    label: 'Cancel',
    disabled: false,
    textColor: theme.colors.white,
    backgroundColor: theme.colors.gray700,
    borderColor: theme.colors.gray700,
    ...props.cancelButton
  };
  const handleCancel = () => {
    if (cancelButton?.onClick) {
      cancelButton.onClick();
    } else {
      close();
    }
  };

  const clickModalContainer = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  return createPortal(
    <ModalOverlay onClick={close}>
      <ModalContainer className={className} onClick={clickModalContainer}>
        <CloseButton onClick={close} />
        {children}
        <ModalButtonsContaier>
          {submitButton.onClick && <ConfirmButton {...submitButton} onClick={submitButton.onClick}>{submitButton.label}</ConfirmButton>}
          {!props.cancelButton ||
            (!cancelButton.disabled && (
              <ConfirmButton className="testId-cancel" {...cancelButton} onClick={handleCancel}>
                {cancelButton.label}
              </ConfirmButton>
            ))}
        </ModalButtonsContaier>
      </ModalContainer>
    </ModalOverlay>,
    document.body
  );
};

export default Modal;
