import css from './index.module.css';
import {FC, FormEventHandler, ReactNode, useEffect} from 'react';
import ReactModal from 'react-modal';
import {CloseCircleFilled} from '@ant-design/icons';
import ModalBtnGroup from './BtnGroup';
import {Space} from 'antd';
import addIcon from '@assets/images/dialog/add.svg';
import editIcon from '@assets/images/dialog/edit.svg';

type ReactModalStyle = ReactModal.Styles;

type Props = {
  visible: boolean;
  title: string;
  onClose?: () => void;
  isLoading?: boolean;
  onSubmit?: FormEventHandler<HTMLFormElement>;
  children?: ReactNode;
  testId?: string;
  height?: string;
  width?: string;
  icon?: string;
};

const Modal: FC<Props> = function ({
  visible,
  title,
  onClose,
  isLoading,
  onSubmit,
  children,
  testId,
  height,
  width,
  icon,
}) {
  const styles: ReactModalStyle = {
    content: {
      width: width ?? '680px',
      overflow: 'visible',
      borderRadius: '10px',
      height: height ?? '600px',
    },
  };

  useEffect(
    function () {
      if (visible) {
        document.body.classList.add('lock-scroll');
      } else {
        document.body.classList.remove('lock-scroll');
      }
    },
    [visible],
  );

  const isAdd = title.includes('新增');
  return (
    <ReactModal
      isOpen={visible}
      style={styles}
      closeTimeoutMS={200}
      ariaHideApp={false}
      shouldCloseOnOverlayClick
      onRequestClose={onClose}
    >
      <section className={css.dialog} data-testid={testId}>
        <div className={css.dialogTitle}>
          <h3>{title}</h3>
        </div>

        <CloseCircleFilled className={css.dialogClose} onClick={onClose} />

        <div className={css.dialogDecorate}>
          <span className={css.dialogDecorateIcon1} />
          <div className={css.dialogDecorateCircle}>
            <img src={icon ? icon : isAdd ? addIcon : editIcon} />
          </div>
          <span className={css.dialogDecorateIcon2} />
        </div>

        <form onSubmit={onSubmit} className={css.dialogForm}>
          <div className={css.dialogContent}>
            <Space direction='vertical' size={0} className='width-full'>
              {children}
            </Space>
          </div>
          <ModalBtnGroup isLoading={isLoading} onClose={onClose} />
        </form>
      </section>
    </ReactModal>
  );
};

export default Modal;
