import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Divider, Modal, Space } from '@easyv/antd';
import { ModalProps } from '@easyv/antd/lib/modal';
import EasyvButton from 'components/EasyvButton';
import styles from './style.less';
import classNames from 'classnames';

export interface ActionModalProps extends ModalProps {
  content?: string | React.ReactNode;
  maxHeight?: React.CSSProperties['maxHeight']; //允许重写body最大高度
}

export interface ActionModalRef {
  show: () => void;
  close: () => void;
}

const ActionModal = forwardRef<ActionModalRef, ActionModalProps>((props, ref) => {
  const {
    width = 530,
    footer,
    onCancel = () => setVisible(false),
    onOk,
    content,
    className,
    maxHeight,
    okText = '确认',
    ...otherProps
  } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const defaultFooter = (
    <Space>
      <EasyvButton theme="default" onClick={onCancel}>
        取消
      </EasyvButton>
      <EasyvButton
        theme="primary"
        onClick={(e) => {
          onOk && onOk(e);
          setVisible(false);
        }}>
        {okText}
      </EasyvButton>
    </Space>
  );

  // useEffect(() => {
  //   const onConfirm = (e) => {
  //     if (visible && e && e.keyCode == 13) {
  //       onOk?.(e);
  //       setVisible(false);
  //     }
  //   };

  //   document.addEventListener('keydown', onConfirm, false);

  //   return () => {
  //     document.removeEventListener('keydown', onConfirm, false);
  //   };
  // }, [visible]);

  useImperativeHandle(ref, () => ({
    show: () => {
      setVisible(true);
    },
    close: () => {
      setVisible(false);
    }
  }));

  return (
    <Modal
      {...otherProps}
      width={width}
      bodyStyle={{ backgroundColor: 'var(--easyv-background-6)', maxHeight }}
      className={classNames(styles.actionModalWrapper, className)}
      destroyOnClose={true}
      keyboard={true}
      onCancel={onCancel}
      visible={visible}
      footer={footer === null ? '' : footer || defaultFooter}>
      <Divider type="horizontal" className={styles.horizontal} />
      <div>{content}</div>
    </Modal>
  );
});

export default ActionModal;

export const useActionModalRef = () => {
  return useRef<ActionModalRef>(null);
};
