import React, { forwardRef, useImperativeHandle, useRef, useState, useEffect } from 'react';
import { Modal, Space } from '@easyv/antd';
import { ModalProps } from '@easyv/antd/lib/modal';
import EasyvButton from 'components/EasyvButton';
import styles from './style.less';
import ExclamationCircleFilled from '@ant-design/icons/lib/icons/ExclamationCircleFilled';

interface ConfirmProps extends ModalProps {
  content: string | React.ReactNode;
  iconType?: 'info' | 'warning' | 'error'; //icon主题色，蓝色｜黄色｜红色
  cancelBtnType?: 'danger' | 'primary' | 'default'; //取消按钮主题色
  onOkBtnType?: 'danger' | 'primary' | 'default'; //确认按钮主题色
  maxHeight?: React.CSSProperties['maxHeight']; //允许重写body最大高度
}

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

const iconColor = {
  info: '#2175F3',
  warning: '#E79E31',
  error: '#C8474E'
};

const Confirm = forwardRef<ConfirmRef, ConfirmProps>((props, ref) => {
  const {
    width = 400,
    title = '提示',
    content,
    footer,
    iconType = 'warning',
    onCancel = () => setVisible(false),
    cancelBtnType = 'default',
    onOkBtnType = 'danger',
    onOk,
    cancelText = '取消',
    okText = '确定',
    maxHeight,
    ...otherProps
  } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const defaultFooter = (
    <Space>
      <EasyvButton theme={cancelBtnType} onClick={onCancel}>
        {cancelText}
      </EasyvButton>
      <EasyvButton
        theme={onOkBtnType}
        onClick={(e) => {
          onOk && onOk(e);
          setVisible(false);
        }}>
        {okText}
      </EasyvButton>
    </Space>
  );
  useImperativeHandle(ref, () => ({
    show: () => {
      setVisible(true);
    },
    close: () => {
      setVisible(false);
    }
  }));
  useEffect(() => {
    const onConfirm = (e) => {
      if (visible && e?.keyCode == 13) {
        onOk?.(e);
        setVisible(false);
      }
    };

    visible && document.addEventListener('keydown', onConfirm, false);

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

  return (
    <Modal
      width={width}
      bodyStyle={{ backgroundColor: 'var(--easyv-background-6)', maxHeight }}
      className={styles.confirmModalWrapper}
      {...otherProps}
      visible={visible}
      closable={false}
      title={null}
      destroyOnClose
      footer={footer ? footer : defaultFooter}>
      <div className={styles.header}>
        <span className={styles.headerIcon}>
          <ExclamationCircleFilled style={{ color: iconColor[iconType] }} />
        </span>
        <span className={styles.tipTitle}>{title}</span>
      </div>
      <div className={styles.content}>{content}</div>
    </Modal>
  );
});

export default Confirm;

export const useConfirmRef = () => {
  return useRef<ConfirmRef>(null);
};
