import React, { useEffect, useState } from 'react';
import { Tooltip } from '@easyv/antd';
import message from 'components/message';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import styles from './AccessKeyModal.less';
import EasyvModal, { useActionModalRef } from './EasyvModal';
import EasyvButton from './EasyvButton';

const AccessKeyModal = ({ children }: { children: React.ReactElement[] }) => {
  const modalRef = useActionModalRef();
  const [secretShow, setSecretShow] = useState<boolean>(false);
  const [current, setCurrent] = useState<number>();
  const [tooltipVisible, setTooltipVisible] = useState<boolean>(false);
  const [data, setData] = useState<{ accessId?: string; accessSecret?: string }>();

  useEffect(() => {
    request(api.accessKeys).then((res) => {
      if (res) {
        setData(res);
      }
    });
  }, []);

  const showSecret = () => {
    setSecretShow(true);
  };

  const hideSecret = () => {
    setSecretShow(false);
  };

  const copyText = (text) => {
    const oInput = document.createElement('input');
    oInput.value = text;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令
    oInput.style.display = 'none';
    document.body.removeChild(oInput);
    message.success('复制成功');
  };

  const tooltipConfirm = () => {
    // 确认重置 todo
    request(
      api.accessKeysReset,
      { accessId: data?.accessId },
      undefined,
      JSON.stringify({ accessSecret: '' }),
    ).then((res) => {
      if (res) {
        setData(res);
        setTooltipVisible(false);
        message.success('重置成功');
      }
    });
  };

  const tooltipCancel = () => {
    setTooltipVisible(false);
  };

  const showTooltip = () => {
    setTooltipVisible(true);
  };

  const handleClick = (i) => {
    setCurrent(i);
    switch (i) {
      case 1:
        showSecret();
        break;
      case 2:
        copyText(data?.accessSecret);
        break;
      case 0:
        hideSecret();
        break;
      case 3:
        showTooltip();
        break;
      default:
        return;
    }
  };

  const secrectToStar = (secret = '') => {
    return new Array(secret.length).join('*');
  };

  const popoverContent = (
    <div className={styles.popoverContent}>
      <div className={styles.title}>重置后，之前的Accesskey Secret将会失效，是否确认重置？</div>
      <div className={styles.buttons}>
        <EasyvButton theme="default" className={styles.btn} onClick={tooltipCancel}>
          取消
        </EasyvButton>
        <EasyvButton
          theme="primary"
          className={styles.btn}
          style={{ marginLeft: '8px' }}
          onClick={tooltipConfirm}>
          确认
        </EasyvButton>
      </div>
    </div>
  );
  return (
    <span>
      <span
        onClick={() => modalRef.current?.show()}
        style={{ display: 'flex', alignItems: 'center' }}>
        {children}
      </span>
      <EasyvModal.ActionModal
        ref={modalRef}
        title="Accesskey"
        width={560}
        footer={null}
        className={styles.customModal}
        onCancel={() => {
          tooltipCancel();
          modalRef.current?.close();
        }}
        content={
          <>
            <div className={styles.row}>
              <div className={styles.text}>
                <span>Accesskey ID:</span>
                <span style={{ color: '#B4B7C1' }}>{data?.accessId}</span>
              </div>
              <div
                className={styles.iconWrap}
                style={{ cursor: 'pointer' }}
                onClick={() => copyText(data?.accessId)}>
                <i className="icon iconfont" style={{ color: '#fff' }}>
                  &#xe618;
                </i>
                <span className={current === 2 ? styles.active : ''}>复制</span>
              </div>
            </div>
            <div className={styles.row}>
              <div className={styles.text}>
                <span>Accesskey Secret:</span>
                {
                  <span style={{ color: '#B4B7C1' }} className={secretShow ? '' : styles.secrect}>
                    {secretShow ? data?.accessSecret : secrectToStar(data?.accessSecret)}
                  </span>
                }
              </div>

              <div className={styles.iconGroup}>
                {secretShow ? (
                  <div className={styles.iconWrap} onClick={() => handleClick(0)}>
                    <i
                      className="icon iconfont"
                      style={{ color: current === 1 ? '#2491f7' : '#fff' }}>
                      &#xe605;
                    </i>
                    <span className={current === 1 ? styles.active : ''}>隐藏</span>
                  </div>
                ) : (
                  <div className={styles.iconWrap} onClick={() => handleClick(1)}>
                    <i
                      className="icon iconfont"
                      style={{ color: current === 0 ? '#2491f7' : '#fff' }}>
                      &#xe604;
                    </i>
                    <span className={current === 0 ? styles.active : ''}>显示</span>
                  </div>
                )}

                <div className={styles.iconWrap} onClick={() => handleClick(2)}>
                  <i
                    className="icon iconfont"
                    style={{ color: current === 2 ? '#2491f7' : '#fff' }}>
                    &#xe618;
                  </i>
                  <span className={current === 2 ? styles.active : ''}>复制</span>
                </div>
                <Tooltip
                  placement="top"
                  title={popoverContent}
                  trigger={'click'}
                  overlayClassName={styles.customAccesskeyTooltip}
                  visible={tooltipVisible}>
                  <div className={styles.iconWrap} onClick={() => handleClick(3)}>
                    <i
                      className="icon iconfont"
                      style={{ color: current === 3 ? '#2491f7' : '#fff' }}>
                      &#xe612;
                    </i>
                    <span className={current === 3 ? styles.active : ''}>重置</span>
                  </div>
                </Tooltip>
              </div>
            </div>
          </>
        }
      />
    </span>
  );
};
export default AccessKeyModal;
