// @ts-nocheck
import React, { useState, useCallback } from 'react';
import styles from './styles.less';
import { FM, FormattedMessage } from '@/locales';
import Agreement from '@/components/agreement';
import { DownOutlined, UpOutlined } from '@ant-design/icons';

import { loginService, commonService } from '@/service';

import { Form, Button, message, Row, Col } from 'antd4';

import BaseForm from '@/components/form';

import {
  Phone,
  Captcha,
  Input,
  Password,
  Email,
  Select,
} from '@/components/form_items';

const RegisterByEmailForm = (props) => {
  const [registerByEmailForm] = Form.useForm();
  const initialValues = {
    agreement: true,
  };

  const email_pattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);
  const [formValidate, setFormValidate] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isExpand, setIsExpand] = useState(false);

  const [lastTime, setLastTime] = useState();
  const { positions, subjects } = props;

  const handleFormFinish = (values) => {
    const payload = {
      username: values.username,
      code: values.captcha,
      email: values.email,
      password: values.password,
      nickname: values.nickname,
      title: values.title || '',
      subject: values.subject || '',
    };
    if (props?.onFinish) {
      props.onFinish(payload, setLoading);
    }
  };

  const handleValuesChange = (changed, values) => {
    if (changed.email) {
      let email_enable = email_pattern.test(changed.email);
      if (email_enable && !captchaEnable) {
        setCaptchaEnable(true);
      } else if (!email_enable && captchaEnable) {
        setCaptchaEnable(false);
      }
    }
    setFormValues(values);
  };

  const handleCaptchaSend = async () => {
    try {
      const payload = { email: formValues.email };
      const data = await loginService.sendCodeToEmailUnRegistered(payload);
      if (data?.error) {
        throw new Error(data?.msg);
      }
      setLastTime(new Date().getTime());
      message.success('验证码发送成功，请查收!');
    } catch (e) {
      if (e?.message === '60秒内不能发送多次验证码') {
        message.error(e?.message);
      } else {
        message.error('验证码发送失败，请稍候重试!');
      }
    }
  };

  return (
    <BaseForm
      form={registerByEmailForm}
      initialValues={initialValues}
      name="registerByEmail"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
      onFieldsChange={(_, allFields) => {
        setFormValidate(
          allFields
            .slice(0, 4)
            .every(({ touched, errors }) => touched && errors?.length === 0),
        );
      }}
    >
      <Email
        isShowMask
        rules={[
          {
            required: true,
            message: FormattedMessage({
              id: 'common.sign.up.email.input.require.message',
              defaultMessage: 'email cannot be empty',
            }),
          },
          {
            pattern: email_pattern,
            message: FormattedMessage({
              id: 'common.sign.up.email.input.right.message',
              defaultMessage: 'Please enter the correct email',
            }),
          },
          () => ({
            validator(_, value) {
              return new Promise(async (resolve, reject) => {
                if (!email_pattern.test(value)) {
                  resolve();
                } else {
                  const payload = { email: value };
                  const data = await commonService.checkIsExistEmail(payload);
                  if (data && data.error) {
                    reject(
                      new Error(
                        FormattedMessage({
                          id: 'common.sign.up.account.input.exist.message',
                          defaultMessage: 'Account already exists',
                        }),
                      ),
                    );
                  } else {
                    resolve();
                  }
                }
              });
            },
          }),
        ]}
      />

      <Captcha
        isShowMask
        enable={captchaEnable}
        // rules={[
        //   {
        //     required: true,
        //     message: '验证码不能为空',
        //   },
        //   {
        //     pattern: /^[0-9]{6}$/,
        //     message: '请输入正确的验证码',
        //   },
        // ]}
        onSend={handleCaptchaSend}
        lastTime={lastTime}
      />

      <Password
        isShowMask
        placeholder={FormattedMessage({
          id: 'common.sign.up.account.pwd.input.placement',
          defaultMessage: 'Please enter the password',
        })}
        // placeholder={'请输入密码，建议六位以上带有特殊符号'}
      />

      <Password
        isShowMask
        name="confirm"
        dependencies={['password']}
        placeholder={FormattedMessage({
          id: 'common.reset.pwd.repeat.pwd.input.placement',
          defaultMessage: 'Please enter the password again',
        })}
        rules={[
          {
            required: true,
            message: FormattedMessage({
              id: 'common.reset.pwd.repeat.pwd.input.placement',
              defaultMessage: 'Please enter the password again',
            }),
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(
                new Error(
                  FormattedMessage({
                    id: 'common.reset.pwd.repeat.pwd.input.noteq',
                    defaultMessage: 'The two passwords are inconsistent',
                  }),
                ),
              );
            },
          }),
        ]}
      />
      <div
        style={{
          fontSize: '12px',
          color: '#1679ff',
          cursor: 'pointer',
          marginTop: '-12px',
          marginBottom: '5px',
        }}
        onClick={() => setIsExpand((isExpand) => !isExpand)}
      >
        {isExpand ? (
          <>
            <FM id="common.less" />
            <UpOutlined />
          </>
        ) : (
          <>
            <FM id="common.tip" />
            <DownOutlined />
          </>
        )}
      </div>
      {isExpand ? (
        <>
          <Input
            name={'nickname'}
            placeholder={FormattedMessage({
              id: 'common.sign.up.account.nickname.input.placement',
              defaultMessage: 'Please enter nickname',
            })}
          />

          <Row gutter={10}>
            <Col span={12}>
              <Select
                placeholder={FormattedMessage({
                  id: 'common.sign.up.account.title.input.placement',
                  defaultMessage: 'Please enter title',
                })}
                name={'title'}
                key={'email'}
                optionList={positions}
              />
            </Col>
            <Col span={12}>
              <Select
                placeholder={FormattedMessage({
                  id: 'common.sign.up.account.subject.input.placement',
                  defaultMessage: 'Please enter subject',
                })}
                name={'subject'}
                key={'email'}
                optionList={subjects}
              />
            </Col>
          </Row>
        </>
      ) : null}
      <Button
        type="primary"
        htmlType="submit"
        loading={loading}
        disabled={!formValidate}
      >
        <FM id="common.sign.up.account.title" defaultMessage="Register" />
      </Button>
      <div className={styles.agreementInfoGroup}>
        <Agreement />

        <div className={styles.goLoginGroup}>
          <span>
            <FM
              id="common.sign.up.account.back.title"
              defaultMessage="Already have an AMiner account"
            />
          </span>
          <a onClick={props?.handleGoLoginGroup} style={{ marginLeft: '5px' }}>
            <FM
              id="common.sign.up.account.login.title"
              defaultMessage="log in directly"
            />
          </a>
        </div>
      </div>
    </BaseForm>
  );
};

export default RegisterByEmailForm;
