// @flow

import * as React from 'react';
import { createFragmentContainer, graphql } from 'react-relay/compat';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import Button from 'app/components/shared/Button';
import Dialog from 'app/components/shared/Dialog';
import RecoveryCodeList from 'app/components/RecoveryCodeList';
import type { RecoveryCodeDialog_totp } from './__generated__/RecoveryCodeDialog_totp.graphql';

type Props = {
  onRequestClose: Function,
  totp: RecoveryCodeDialog_totp
};

type RecoveryCodes = $PropertyType<RecoveryCodeDialog_totp, 'recoveryCodes'>;

function recoveryCodeText(recoveryCodes: RecoveryCodes): ?string {
  if (recoveryCodes && recoveryCodes.codes) {
    return recoveryCodes.codes.reduce((memo, { code }) => memo.concat(code), []).join('\n');
  }
  return '';
}

class RecoveryCodesDialog extends React.PureComponent<Props> {
  render() {
    return (
      <Dialog isOpen={true} onRequestClose={this.props.onRequestClose} width={540}>
        <div className="p4">
          <h2 className="m0 h2 semi-bold mb5">Current Recovery Codes</h2>
          <p>Recovery codes are used if you lose access to your code generator.</p>
          <RecoveryCodeList recoveryCodes={this.props.totp.recoveryCodes} />
          <p>These codes should be treated just like your password. Weʼd suggest saving them into a secure password manager.</p>
          <CopyToClipboard
            text={recoveryCodeText(this.props.totp.recoveryCodes)}
            onCopy={this.handleRecoveryCodeCopy}
          >
            <Button className="col-12" theme="success" outline={true}>
              Copy Recovery Codes
            </Button>
          </CopyToClipboard>
        </div>
      </Dialog>
    );
  }

  handleRecoveryCodeCopy = (_text, result) => {
    if (!result) {
      alert('We couldnʼt put this on your clipboard for you, please copy it manually!');
    }
  }
}

export default createFragmentContainer(RecoveryCodesDialog, {
  totp: graphql`
    fragment RecoveryCodeDialog_totp on TOTP {
      id
      recoveryCodes {
        id
        ...RecoveryCodeList_recoveryCodes
        codes {
          code
          consumed
        }
      }
    }
  `
});

@@ -507,16 +507,67 @@
 otp%0A%7D;%0A%0A
+%0Atype State = %7B%0A  copiedRecoveryCodes: boolean%0A%7D;%0A%0A
 type Rec
@@ -922,19 +922,76 @@
 nt%3CProps
-%3E %7B
+, State%3E %7B%0A  state = %7B%0A      copiedRecoveryCodes: false%0A  %7D%0A
 %0A  rende
@@ -1710,28 +1710,147 @@
 e=%7Bt
-rue%7D%3E%0A              
+his.state.copiedRecoveryCodes%7D%3E%0A              %7Bthis.state.copiedRecoveryCodes%0A                ? 'Copied Recovery Codes'%0A                : '
 Copy
@@ -1860,24 +1860,26 @@
 covery Codes
+'%7D
 %0A           
@@ -2117,22 +2117,72 @@
 lly!');%0A
-
     %7D%0A
+    this.setState(%7B copiedRecoveryCodes: true %7D);%0A
   %7D%0A%7D%0A%0Ae

Check state in RecoveryCodeDialog copied state