import React, {useEffect, useRef, useState} from 'react';
import {Manager} from 'react-popper';
import {Popper} from 'react-popper';
import {Reference} from 'react-popper';
import copy from 'copy-to-clipboard';
import {t} from './i18n';

export function WalletAddress(props) {
  const [showPopup, setShowPopup] = useState(false);
  const {symbol, id, name} = props;
  const walletIdRef = useRef(null);

  const buttonClicked = (e) => {
    setShowPopup(true);
    const walletId = walletIdRef.current;
    const value = walletId.getAttribute('value');
    copy(value);
  };

  const renderPopper = () => {
    const classes = ['notify-popup'];
    if (showPopup) {
      classes.push('start');
    }
    return (
      <Popper placement="top">
        {({ref, style, placement, arrowProps}) => (
          <div className={classes.join(' ')} ref={ref} style={style} data-placement={placement}>
            { t('t-copied') }
            <div className="arrow" ref={arrowProps.ref} style={arrowProps.style} />
          </div>
        )}
      </Popper>
    );
  };

  useEffect(() => {
    if (showPopup) {
      setTimeout(() => { setShowPopup(false); }, 100);
    }
  }, [showPopup]);

  const popup = renderPopper();

  return (
    <li>
      <div className="currency-name">{ name } ({ symbol })</div>
      <input ref={walletIdRef} className="wallet-id" type="text" value={id} readOnly />
      <Manager>
        <Reference>
          {({ref}) => (
            <button type="button" className="copy-button" ref={ref} onClick={buttonClicked}></button>
          )}
        </Reference>
        {popup}
      </Manager>
    </li>
  );
}
