/**
 * Title: 获取矿晶
 * Routes:
 *   - ./src/pages/routes
 */
import React, { useEffect } from 'react';
import { connect, DispatchProp } from 'dva';
import { Spin, Input, Select, Icon, Button, message, Modal } from 'antd';
import { formatMessage } from 'umi-plugin-locale';
import { DrawModelState } from './model';
import { PageState } from '@/types/common';
import Header from '@/components/Header';

import styles from './style.less';
import h5plus from '@/utils/h5plus';
import { displayLabel } from '@/utils/transform';

const Option = Select.Option;

const DrawPage: React.FC<DispatchProp & DrawModelState> = ({
  dispatch,
  pageState,
  coin,
  coins,
  balance,
  address,
  amount,
  fee,
  actual,
  confirmVisible,
  confirmLoading,
  password,
}) => {
  useEffect(() => {
    dispatch({ type: 'draw/load' });
  }, []);

  let body;
  if (pageState === PageState.Pending) {
    body = (
      <Spin className={styles.none} />
    );
  } else if (pageState === PageState.Failure) {
    body = (
      <div className={styles.none}>{formatMessage({ id: 'common.loadError' })}</div>
    );
  } else if (pageState === PageState.Success) {
    const coinLabel = displayLabel(coin && coin.label);
    const onScan = async () => {
      if (h5plus.isApp()) {
        const result = await h5plus.scan();
        if (result) {
          dispatch({ type: 'draw/onUpdateState', address: result });
        } else {
          message.warn(formatMessage({ id: 'draw.qrError' }));
        }
      } else {
        message.warn(formatMessage({ id: 'draw.qrPrompt' }));
      }
    }
    const confirmContent = (
      <Modal
        visible={confirmVisible}
        onCancel={() => dispatch({ type: 'draw/onUpdateState', confirmVisible: false })}
        onOk={() => dispatch({ type: 'draw/draw' })}
        okText={formatMessage({ id: 'common.ok' })}
        cancelText={formatMessage({ id: 'common.cancel' })}
        confirmLoading={confirmLoading}
        title={formatMessage({ id: 'common.prompt' })}
        maskClosable={false}
      >
        <span style={{ wordBreak: 'break-all' }}>
          {formatMessage(
            { id: 'draw.summary' },
            { num: amount, coin: coinLabel, address },
          )}
        </span>
        <div style={{ marginTop: 24 }}>
          <span>{formatMessage({ id: 'draw.pwdPrompt' })}</span>
          <Input
            style={{ marginTop: 8 }}
            value={password}
            onChange={e => dispatch({ type: 'draw/onUpdateState', password: e.target.value })}
            type="password"
          />
        </div>
      </Modal>
    );
    body = (
      <>
        <div className={styles.section}>
          <div className="coin-selection">
            <span>{formatMessage({ id: 'draw.selection' })}</span>
            <Select
              size="small"
              value={coin && coin.id}
              onChange={(payload: any) => dispatch({ type: 'draw/selectCoin', payload })}
            >
              {coins.map(it => (
                <Option
                  key={it.id}
                  value={it.id}
                >{displayLabel(it.label)}</Option>
              ))}
            </Select>
          </div>
        </div>

        <div
          className={`${styles.section}`}
        >
          <div>{formatMessage({ id: 'draw.target' }, { label: coinLabel })}</div>
          <Input
            value={address}
            className="app-input"
            placeholder={formatMessage({ id: 'draw.placeholder' })}
            suffix={<Icon onClick={onScan} type="scan" />}
            onChange={e => dispatch({ type: 'draw/changeAddress', payload: e.target.value })}
          />
        </div>

        <div className={styles.section}>
          <div className="with-postfix">
            <span>{formatMessage({ id: 'draw.amount' })}</span>
            <span className="small-info">
              {formatMessage(
                { id: 'draw.avaliable' },
                { num: balance || 0, coin: coinLabel },
              )}
            </span>
          </div>
          <Input
            className="app-input"
            placeholder={formatMessage({ id: 'draw.drawHint' })}
            addonAfter={coinLabel}
            type="number"
            value={amount}
            onChange={e => dispatch({ type: 'draw/changeAmount', payload: e.target.value })}
          />
          <div className="small-info right">
            {formatMessage({ id: 'draw.fee' }, { num: fee || 0, coin: coinLabel })}
          </div>
          <div className="small-info right">
            {formatMessage({ id: 'draw.actual' }, { num: actual || 0, coin: coinLabel })}
          </div>
        </div>

        <div className={styles.section}>
          <div>{formatMessage({ id: 'draw.condition' }, { label: coinLabel })}</div>
        </div>

        <Button
          type="primary"
          className={styles.btn}
          onClick={() => dispatch({ type: 'draw/performDraw' })}
        >
          {formatMessage({ id: 'draw.draw' })}
        </Button>

        {confirmContent}
      </>
    );
  }

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

      <div className={styles.body}>
        <div className={styles.card}>{body}</div>
      </div>
    </div>
  );
};

export default connect(
  ({ draw }: any) => ({ ...draw }),
)(DrawPage);
