import { Input, Modal } from 'antd';
import style from './index.less';
import { useState } from 'react';
import { useIntl } from 'umi';
import React from 'react';

type OneKeyCopyProps = {
  callback: () => void;
  children: React.ReactNode;
};

const OneKeyCopyModal: React.FC<OneKeyCopyProps> = ({ callback, children }) => {
  const [value, setValue] = useState('');
  const [isShowErrorTip, setIsShowErrorTip] = useState(false);
  const [open, setOpen] = useState(false);
  const { formatMessage } = useIntl();

  const compareValue = () => {
    if (value === formatMessage({ id: 'component.oneKeyCopy.confirmOperation' })) {
      setIsShowErrorTip(false);
      setOpen(false);
      setValue('');
      callback();
    } else {
      setIsShowErrorTip(true);
    }
  };

  const triggerRender = () => {
    if (!React.isValidElement(children)) {
      return <a onClick={() => setOpen(true)}>{children}</a>;
    }

    return React.cloneElement(children as React.ReactElement<any>, {
      onClick: () => {
        setOpen(true);
      },
    });
  };

  return (
    <div onClick={(event) => event.stopPropagation()}>
      <Modal
        title={formatMessage({ id: 'component.oneKeyCopy.notice' })}
        className={style.modal}
        open={open}
        onOk={compareValue}
        onCancel={() => {
          setOpen(false);
          setIsShowErrorTip(false);
          setValue('');
        }}
      >
        <div className={style.content}>{formatMessage({ id: 'component.oneKeyCopy.content' })}</div>
        <div className={style.copyAreaWrap}>
          <div className={style.copyArea}>
            <Input value={value} onChange={(e) => setValue(e.target.value)} />
            <span
              onClick={() =>
                setValue(formatMessage({ id: 'component.oneKeyCopy.confirmOperation' }))
              }
            >
              {formatMessage({ id: 'component.oneKeyCopy.oneKey' })}
            </span>
          </div>
          {isShowErrorTip && (
            <p className={style.messageTips}>{formatMessage({ id: 'component.oneKeyCopy.tip' })}</p>
          )}
        </div>
      </Modal>
      {triggerRender()}
    </div>
  );
};

export default OneKeyCopyModal;
