import React, { useEffect, useLayoutEffect, useState } from 'react';
import {
  Keyboard,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { StackScreenProps } from '@react-navigation/stack';
import { useHeaderHeight } from '@react-navigation/elements';
import { useCountdown } from '@szyx-mobile/hooks';
import { LoginParamList } from '@app/routes/login/LoginParamList.ts';
import SubmitButton from '@common/components/SubmitButton';
import LoginTextInputItem from '../components/LoginTextInputItem';
import { useLoginWithVerifyCode } from './api';
import Spinner from '@common/components/Spinner';
import { useLogin } from '@app/hooks/useLogin';
import { useSMSVerifyCode } from '../api';
import LinearGradient from 'react-native-linear-gradient';
import { showErrorMessage, showMessage } from '@common/ToastHelper.ts';

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

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

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

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

  const login = useLogin();

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

  // 【状态】

  const [smsCode, setSmsCode] = useState(''); // 验证码

  // 【接口】

  const { loading: verifyCodeLoading, fetchAsync: verifyCodeFetch } =
    useSMSVerifyCode(route.params.phoneNumber, 'login'); // 获取验证码
  const { loading: loginLoading, fetchAsync: loginFetch } =
    useLoginWithVerifyCode(route.params.phoneNumber, smsCode);

  // 首次进入的时候一定是已经获取成功验证码了，直接开始倒计时
  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}>
            {/* 手机号需要隐藏中间四位 */}
            {count === null
              ? '验证码正在发送'
              : `验证码已发送至 ${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}
              autoFocus={true}
              onChangeText={value => {
                setSmsCode(value);
              }}
              clearButton={true}
            />
          </View>
          <SubmitButton
            style={styles.loginButton}
            title="确定"
            theme="dark"
            disabled={smsCode.length !== 6}
            onPress={() => {
              Keyboard.dismiss();

              loginFetch()
                .then(r => {
                  showMessage('登录成功');
                  login(r.sessionId, {
                    userId: r.userId,
                    userType: r.userType,
                    moduleList: [],
                    isFirstLogin: true,
                    currentUserType:
                      r.userType === 'general' ? 'general' : 'guanxin',
                    realNameStatus: r.realNameStatus,
                    enableCert: r.enableCert,
                    phone: route.params.phoneNumber,
                    gxLeader: r.gxLeader,
                    hasBindFirm: r.hasBindFirm,
                    hasFaceDetect: r.hasFaceDetect,
                    nickname: undefined,
                    picUrl: undefined,
                    faceDetectFirms: undefined,
                    userIdCardNum: undefined,
                  });
                })
                .catch(e => {
                  showErrorMessage(e.message);
                });
            }}
          />
          {/* 重新获取验证码 */}
          <View style={styles.bottom}>
            <TouchableOpacity
              disabled={count !== null && count > 0}
              onPress={() => {
                verifyCodeFetch()
                  .then(() => {
                    showMessage('验证码已发送');
                    start();
                  })
                  .catch(e => {
                    showErrorMessage(e.message);
                  });
              }}
            >
              <Text
                style={[
                  styles.bottomText,
                  {
                    color:
                      count === null || count === 0
                        ? BUTTON_ACTIVE_COLOR
                        : BUTTON_UNACTIVE_COLOR,
                  },
                ]}
              >{`${
                count === null
                  ? ''
                  : count === 0
                  ? '重发验证码'
                  : `重新获取（${count}）`
              }`}</Text>
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      </ScrollView>
      {(verifyCodeLoading || loginLoading) && <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,
    marginBottom: 65,
  },
  title: {
    fontSize: 24,
    color: '#17171A',
    fontWeight: '600',
  },
  headerText: {
    fontSize: 14,
    color: '#17171A',
    fontWeight: '500',
    marginVertical: 14,
  },
  loginButton: {
    marginHorizontal: 25,
    marginBottom: 20,
    marginTop: 20,
  },
  bottom: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 64,
  },
  bottomText: {
    fontSize: 14,
  },
});
