import React, { useLayoutEffect, useState } from 'react';
import {
  Keyboard,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { StackScreenProps } from '@react-navigation/stack';
import { LoginParamList } from '@app/routes/login/LoginParamList.ts';
import LoginTextInputItem from '../components/LoginTextInputItem';
import SubmitButton from '@common/components/SubmitButton';
import {
  COUNTDOWN_CHANGE_PHONE_KEY,
  ID_CARD_PATTERN,
  PHONE_PATTERN,
  THEME_COLOR,
} from '@common/constants';
import { useCountdown } from '@szyx-mobile/hooks';
import Spinner from '@common/components/Spinner';
import { useSMSVerifyCode } from '../api';
import { useChangePhone } from './api';
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, 'ChangePhone'>;

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

  useLayoutEffect(() => {
    navigation.setOptions({
      title: '更换手机号',
    });
  }, [navigation]);

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

  // 【状态】

  const [username, setUsername] = useState(''); // 用户姓名
  const [idCardNumber, setIdCardNumber] = useState(''); // 身份证号
  const [phone, setPhone] = useState(''); // 手机号
  const [smsCode, setSmsCode] = useState(''); // 验证码

  // 【接口】

  const { loading: verifyCodeLoading, fetchAsync: verifyCodeFetch } =
    useSMSVerifyCode(phone, 'change', username, idCardNumber); // 获取验证码

  const { loading: changePhoneLoading, fetchAsync: changePhoneFetch } =
    useChangePhone(username, idCardNumber, phone, smsCode); // 更改手机号

  return (
    <>
      <View style={styles.header}>
        <Text style={styles.headerText}>
          温馨提示：更换成功后，您只能用新手机号登录APP
        </Text>
      </View>
      <ScrollView
        style={styles.container}
        contentInsetAdjustmentBehavior="scrollableAxes"
        scrollIndicatorInsets={{ right: 1 }}
        keyboardShouldPersistTaps={'handled'}
      >
        <SafeAreaView>
          <View style={styles.middle}>
            <LoginTextInputItem
              icon={require('@app/assets/images/login/login_username.png')}
              placeholder="请输入您的姓名"
              keyboardType="default"
              maxLength={30}
              value={username}
              onChangeText={value => {
                setUsername(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              icon={require('@app/assets/images/login/login_id_card.png')}
              placeholder="请输入您的身份证号"
              keyboardType="default"
              maxLength={18}
              value={idCardNumber}
              onChangeText={value => {
                setIdCardNumber(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              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
              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 (username.length === 0) {
                    showErrorMessage('请输入您的姓名');
                    return;
                  }

                  if (idCardNumber.length === 0) {
                    showErrorMessage('请输入您的身份证号');
                    return;
                  }

                  if (ID_CARD_PATTERN.test(idCardNumber) === false) {
                    showErrorMessage('身份证号格式不正确');
                    return;
                  }

                  if (phone.length === 0) {
                    showErrorMessage('请输入更换的手机号码');
                    return;
                  }

                  if (PHONE_PATTERN.test(phone) === false) {
                    showErrorMessage('手机号格式不正确');
                    return;
                  }
                  verifyCodeFetch()
                    .then(() => {
                      showMessage('验证码已发送');
                      start();
                    })
                    .catch(e => {
                      showErrorMessage(e.message);
                    });
                },
              }}
            />
          </View>
          <SubmitButton
            style={styles.submit}
            title="保存"
            theme="dark"
            onPress={() => {
              if (username.length === 0) {
                showErrorMessage('请输入您的姓名');
                return;
              }

              if (idCardNumber.length === 0) {
                showErrorMessage('请输入您的身份证号');
                return;
              }

              if (ID_CARD_PATTERN.test(idCardNumber) === false) {
                showErrorMessage('身份证号格式不正确');
                return;
              }

              if (phone.length === 0) {
                showErrorMessage('请输入更换的手机号码');
                return;
              }

              if (PHONE_PATTERN.test(phone) === false) {
                showErrorMessage('手机号格式不正确');
                return;
              }

              if (smsCode.length === 0) {
                showErrorMessage('请输入验证码');
                return;
              }

              if (smsCode.length !== SMS_CODE_LENGTH) {
                showErrorMessage('验证码格式不正确');
                return;
              }

              Keyboard.dismiss();
              changePhoneFetch()
                .then(() => {
                  showMessage('更换成功');
                  navigation.pop();
                })
                .catch(e => {
                  showErrorMessage(e.message);
                });
            }}
          />
        </SafeAreaView>
      </ScrollView>
      {(verifyCodeLoading || changePhoneLoading) && <Spinner />}
    </>
  );
}

const styles = StyleSheet.create({
  header: {
    backgroundColor: '#FFF5E5',
    padding: 12,
  },
  headerText: {
    color: '#FF9A08',
  },
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  middle: {
    marginTop: 20,
  },
  submit: {
    marginHorizontal: 25,
    marginBottom: 15,
    marginTop: 20,
  },
});
