import React, { useEffect, useLayoutEffect, useState } from 'react';
import {
  Keyboard,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { StackScreenProps } from '@react-navigation/stack';
import { useHeaderHeight } from '@react-navigation/elements';
import { LoginParamList } from '@app/routes/login/LoginParamList.ts';
import SubmitButton from '@common/components/SubmitButton';
import Spinner from '@common/components/Spinner';
import { PASSWORD_PATTERN, THEME_COLOR } from '@common/constants';
import LoginTextInputItem from '../components/LoginTextInputItem';
import { useResetPassword } from './api';
import LinearGradient from 'react-native-linear-gradient';
import { useSMSVerifyCode } from '../api';
import { useCountdown } from '@szyx-mobile/hooks';
import Toast from 'react-native-toast-message';
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, 'ForgotPassword'>;

export default function ForgotPasswordScreen(props: Props) {
  const {navigation, route} = props;
  const headerHeight = useHeaderHeight();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: '',
      headerTransparent: true,
    });
  }, [navigation]);

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

  // 【状态】

  const [smsCode, setSmsCode] = useState(''); // 验证码
  const [password, setPassword] = useState(''); // 密码
  const [passwordAgain, setPasswordAgain] = useState(''); // 再次输入密码

  // 【接口】

  const {loading: verifyCodeLoading, fetchAsync: verifyCodeFetch} =
    useSMSVerifyCode(route.params.phoneNumber, 'reset'); // 获取验证码
  const {loading: resetPasswordLoading, fetchAsync: resetPasswordFetch} =
    useResetPassword(route.params.phoneNumber, smsCode, password);

  // 首次进入的时候一定是已经获取成功验证码了，直接开始倒计时
  useEffect(() => {
    start();
  }, [start]);

  return (
    <View style={styles.container}>
      <LinearGradient
        style={styles.background}
        colors={['rgba(197, 234, 255, 1)', 'rgba(197, 234, 255, 0)']}
      />
      <ScrollView
        style={styles.scroll}
        scrollIndicatorInsets={{right: 1}}
        keyboardShouldPersistTaps={'handled'}>
        <View style={[styles.header, {marginTop: headerHeight}]}>
          <Text style={styles.title}>密码重置</Text>
          <Text
            style={
              styles.headerText
            }>{`验证码已发送至 ${route.params.phoneNumber.replace(
            /(\d{3})\d{4}(\d{4})/,
            '$1****$2',
          )}`}</Text>
        </View>
        <SafeAreaView>
          <View>
            <LoginTextInputItem
              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;
                  }
                  verifyCodeFetch()
                    .then(() => {
                      showMessage('验证码已发送');
                      start();
                    })
                    .catch(e => {
                      showErrorMessage(e.message);
                    });
                },
              }}
            />
            <LoginTextInputItem
              placeholder="请输入密码"
              keyboardType="ascii-capable"
              secureTextEntry={true}
              maxLength={12}
              value={password}
              onChangeText={value => {
                setPassword(value);
              }}
              clearButton={true}
            />
            <LoginTextInputItem
              placeholder="确认密码"
              keyboardType="ascii-capable"
              secureTextEntry={true}
              maxLength={12}
              value={passwordAgain}
              onChangeText={value => {
                setPasswordAgain(value);
              }}
              clearButton={true}
            />
          </View>
          <Text style={styles.middleText}>
            密码长度8-12位，支持英文字母、数字与字符，密码必须包含英文加数字
          </Text>
          <SubmitButton
            style={styles.submit}
            title="完成"
            theme="dark"
            disabled={
              smsCode.length !== SMS_CODE_LENGTH ||
              password.length === 0 ||
              passwordAgain.length === 0
            }
            onPress={() => {
              if (PASSWORD_PATTERN.test(password) === false) {
                showErrorMessage(
                  '密码长度8-12位，支持英文字母、数字与字符，密码必须包含英文加数字',
                );
                return;
              }

              if (passwordAgain.length <= 0) {
                showErrorMessage('请再次确认登录密码');
                return;
              }

              if (passwordAgain !== password) {
                showErrorMessage('两次输入的密码不一致');
                return;
              }

              Keyboard.dismiss();

              resetPasswordFetch()
                .then(() => {
                  showErrorMessage('密码重置成功，请重新登录');
                  navigation.pop();
                })
                .catch(e => {
                  showErrorMessage(e.message);
                });
            }}
          />
        </SafeAreaView>
      </ScrollView>
      {(verifyCodeLoading || resetPasswordLoading) && <Spinner />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  background: {
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    height: 168,
  },
  scroll: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 25,
  },
  title: {
    fontSize: 24,
    color: '#17171A',
    fontWeight: '600',
  },
  headerText: {
    fontSize: 14,
    color: '#17171A',
    fontWeight: '500',
    marginVertical: 14,
  },
  middleText: {
    color: '#ED9900',
    fontSize: 12,
    marginHorizontal: 25,
    marginVertical: 8,
  },
  submit: {
    marginHorizontal: 25,
    marginBottom: 20,
    marginTop: 20,
  },
  bottom: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 64,
  },
  bottomText: {
    fontSize: 12,
  },
});
