import React, { useLayoutEffect, useState } from 'react';
import {
  Keyboard,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { LoginParamList } from '@app/routes/login/LoginParamList.ts';
import { StackScreenProps } from '@react-navigation/stack';
import LoginTextInputItem from '../components/LoginTextInputItem';
import SubmitButton from '@common/components/SubmitButton';
import { useCountdown } from '@szyx-mobile/hooks';
import {
  COUNTDOWN_REGISTER_KEY,
  PASSWORD_PATTERN,
  PHONE_PATTERN,
  THEME_COLOR,
} from '@common/constants';
import Spinner from '@common/components/Spinner';
import { useSMSVerifyCode } from '../api';
import { useRegister } from './api';
import { useLogin } from '@app/hooks/useLogin';
import { showErrorMessage, showMessage } from '@common/ToastHelper.ts';

const BUTTON_ACTIVE_COLOR = THEME_COLOR;
const BUTTON_UNACTIVE_COLOR = '#9B9B9B';
const SMS_CODE_LENGTH = 6; // 验证码长度

type Props = StackScreenProps<LoginParamList, 'Register'>;

export default function RegisterScreen(props: Props) {
  const { navigation } = props;

  useLayoutEffect(() => {
    navigation.setOptions({
      title: '用户注册',
    });
  }, [navigation]);

  const { count, start } = useCountdown(59, COUNTDOWN_REGISTER_KEY);

  const login = useLogin();

  // 【状态】

  const [phone, setPhone] = useState(''); // 手机号
  const [smsCode, setSmsCode] = useState(''); // 验证码
  const [nickname, setNickname] = useState(''); // 用户姓名
  const [invitationCode, setInvitationCode] = useState(''); // 团队邀请码
  const [password, setPassword] = useState(''); // 密码
  const [passwordAgain, setPasswordAgain] = useState(''); // 再次输入密码

  // 【接口】

  const { loading: verifyCodeLoading, fetchAsync: verifyCodeFetch } =
    useSMSVerifyCode(phone, 'register'); // 获取验证码
  const { loading: registerLoading, fetchAsync: registerFetch } = useRegister(
    phone,
    smsCode,
    nickname,
    invitationCode,
    password,
  ); // 注册

  return (
    <>
      <ScrollView
        style={styles.container}
        contentInsetAdjustmentBehavior="scrollableAxes"
        scrollIndicatorInsets={{ right: 1 }}
        keyboardShouldPersistTaps={'handled'}
      >
        <SafeAreaView>
          <View>
            <LoginTextInputItem
              required={true}
              icon={require('@app/assets/images/login/login_phone_number.png')}
              placeholder="请输入手机号"
              keyboardType="phone-pad"
              maxLength={11}
              value={phone}
              onChangeText={value => {
                setPhone(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              required={true}
              icon={require('@app/assets/images/login/login_sms_code.png')}
              placeholder="请输入验证码"
              keyboardType="number-pad"
              maxLength={SMS_CODE_LENGTH}
              value={smsCode}
              onChangeText={value => {
                setSmsCode(value);
              }}
              clearButton={true}
              rightButton={{
                title:
                  count === null
                    ? '获取验证码'
                    : count === 0
                    ? '重新获取'
                    : `重新获取（${count}）`,
                color:
                  count === null || count === 0
                    ? BUTTON_ACTIVE_COLOR
                    : BUTTON_UNACTIVE_COLOR,
                onPress: () => {
                  if (count !== null && count > 0) {
                    return;
                  }
                  if (PHONE_PATTERN.test(phone) === false) {
                    showErrorMessage('请输入正确的手机号码');
                    return;
                  }
                  verifyCodeFetch()
                    .then(() => {
                      showMessage('验证码已发送');
                      start();
                    })
                    .catch(e => {
                      showErrorMessage(e.message);
                    });
                },
              }}
            />
            <LoginTextInputItem
              required={true}
              icon={require('@app/assets/images/login/login_username.png')}
              placeholder="请输入您的姓名"
              keyboardType="default"
              maxLength={30}
              value={nickname}
              onChangeText={value => {
                setNickname(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              icon={require('@app/assets/images/login/login_password.png')}
              placeholder="请输入密码(8-12位,含字母和数字)"
              keyboardType="ascii-capable"
              secureTextEntry={true}
              maxLength={12}
              value={password}
              onChangeText={value => {
                setPassword(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              icon={require('@app/assets/images/login/login_password.png')}
              placeholder="请再次输入密码"
              keyboardType="ascii-capable"
              secureTextEntry={true}
              maxLength={12}
              value={passwordAgain}
              onChangeText={value => {
                setPasswordAgain(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              icon={require('@app/assets/images/login/login_invitation_code.png')}
              placeholder="团队邀请码(6位,团队长邀请时下发)"
              keyboardType="ascii-capable"
              maxLength={6}
              value={invitationCode}
              onChangeText={value => {
                setInvitationCode(value);
              }}
              clearButton={true}
            />
          </View>
          <SubmitButton
            style={styles.submit}
            title="注册"
            theme="dark"
            disabled={
              phone.length !== 11 ||
              smsCode.length !== SMS_CODE_LENGTH ||
              nickname.length === 0
            }
            onPress={() => {
              if (PHONE_PATTERN.test(phone) === false) {
                showErrorMessage('请输入正确的手机号码');
                return;
              }
              if (
                password.length > 0 &&
                PASSWORD_PATTERN.test(password) === false
              ) {
                showErrorMessage(
                  '密码长度8-12位，支持英文字母、数字与字符，密码必须包含英文加数字',
                );
                return;
              }
              if (passwordAgain !== password) {
                showErrorMessage('两次输入的密码不一致');
                return;
              }
              if (invitationCode.length > 0 && invitationCode.length !== 6) {
                showErrorMessage('团队邀请码应为6位');
                return;
              }

              Keyboard.dismiss();

              registerFetch()
                .then(r => {
                  showMessage('注册成功');
                  login(r.sessionId, {
                    userId: r.userId,
                    userType: r.userType,
                    moduleList: [],
                    isFirstLogin: true,
                    currentUserType:
                      r.userType === 'general' ? 'general' : 'guanxin',
                    enableCert: r.enableCert,
                    realNameStatus: r.realNameStatus,
                    phone: phone,
                    gxLeader: r.gxLeader,
                    hasBindFirm: r.hasBindFirm,
                    hasFaceDetect: r.hasFaceDetect,
                    nickname: undefined,
                    picUrl: undefined,
                    faceDetectFirms: undefined,
                    userIdCardNum: undefined,
                  });
                })
                .catch(e => {
                  showErrorMessage(e.message);
                });
            }}
          />
          <Text style={styles.bottomText}>
            电子签名用户请联系管理员注册，请勿自行注册
          </Text>
        </SafeAreaView>
      </ScrollView>
      {(verifyCodeLoading || registerLoading) && <Spinner />}
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  submit: {
    marginHorizontal: 25,
    marginBottom: 15,
    marginTop: 20,
  },
  bottomText: {
    color: '#EB4900',
    textAlign: 'center',
    marginHorizontal: 25,
    fontSize: 12,
    marginBottom: 20,
  },
});
