/**
 * Title: 邀请新人
 * Routes:
 *   - ./src/pages/routes
 */
import React, { useEffect, useState } from 'react';
import { connect, DispatchProp } from 'dva';
import { Icon, Button, message } from 'antd';
import { formatMessage } from 'umi-plugin-locale';
import { QRCanvas } from 'qrcanvas-react';
import Clipboard from 'react-clipboard.js';
import { InviteModelState } from './model';
import Header from '@/components/Header';

import styles from './style.less';
import { UserModelState } from '@/models/user';
import { generateInviteHref } from './service';
import { isApp, share } from '@/utils/h5plus';

const InvitePage: React.FC<DispatchProp & InviteModelState & UserModelState> = ({
  dispatch,
  user,
}) => {
  if (!user) return null;

  useEffect(() => {
    dispatch({ type: 'invite/load' });
  }, []);
  const href = generateInviteHref(user.inviteCode);
  const onAddressCopied = () => {
    message.success(formatMessage({ id: 'common.copied' }));
  };

  return (
    <div className={styles.container}>
      <Header
        className="header"
        title={formatMessage({ id: 'invite.title' })}
      />

      <div className={styles.body}>
        <span className={styles.title2}>{formatMessage({ id: 'invite.title2' })}</span>
        <div className={styles.card}>
          <div className="rip" />
          <div className="content">
            <span className="title3">{formatMessage({ id: 'invite.title3' })}</span>
            <span className="invite-code">{user.inviteCode}</span>
            <QRCanvas options={{
              data: href,
              size: 200,
            }} />
            <div className="href-container">
              <span>{href}</span>
              <Clipboard
                component="div"
                className="address"
                data-clipboard-text={href}
                onSuccess={onAddressCopied}
              >
                <Icon type="copy" theme="filled" />
              </Clipboard>
            </div>
            {isApp() && (
              <Button
                type="primary"
                onClick={() => share(href)}
              >
                {formatMessage({ id: 'invite.btn' })}
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default connect(
  ({ invite, user }: any) => ({ ...invite, ...user }),
)(InvitePage);
