import {
  View,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Keyboard,
  ScrollView,
} from "react-native";
import React, { useContext } from "react";
import { useTailwind } from "tailwind-rn";
import { Formik } from "formik";
import { Button } from "@rneui/themed";
import Toast from "react-native-toast-message";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AuthContext } from "../../../App";
import { cryptoPassword, generateSignature } from "../../../utils/crypto";
import baseRequest from "../../../utils/baseRequest";
import MyDivider from "../../../components/MyDivider";

export default function SetPassword({ navigation, route }) {
  const { signIn } = useContext(AuthContext);
  const insets = useSafeAreaInsets();
  const tailwind = useTailwind();
  //获取环境变量
  const apiUrl = process.env.EXPO_PUBLIC_API_URL;
  //接收登录上级页面传递的登录成功data
  const { data, mobile_phone, region_code, mobilePhone } = route.params;
  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <ScrollView
        style={{
          paddingTop: insets.top,
          paddingBottom: insets.bottom,
          paddingLeft: insets.left,
          paddingRight: insets.right,
          ...tailwind("flex-1 flex-col"),
        }}
      >
        <Formik
          initialValues={{ password: "", confirm_password: "" }}
          onSubmit={async (values) => {
            if (values.password.length < 8) {
              Toast.show({
                type: "error",
                text1: "密码不得小于8位",
                topOffset: 60,
              });
              return;
            }
            if (values.password.length > 15) {
              Toast.show({
                type: "error",
                text1: "密码不得大于15位",
                topOffset: 60,
              });
              return;
            }
            if (!values.confirm_password) {
              Toast.show({
                type: "error",
                text1: "请再次输入您的密码",
                topOffset: 60,
              });
              return;
            }
            if (values.password != values.confirm_password) {
              Toast.show({
                type: "error",
                text1: "两次输入密码不一致",
                topOffset: 60,
              });
              return;
            }
            //MD5加密password
            const encryptedPassword = await cryptoPassword(values.password);
            //设置密码并登录
            const base = await baseRequest();
            const signature = await generateSignature({
              mobile_phone: mobile_phone,
              region_code: region_code,
              new_password: encryptedPassword,
              ...base,
            });
            try {
              const response = await fetch(
                `${apiUrl}/api/login/set_password?signature=${signature}`,
                {
                  method: "POST",
                  headers: {
                    "Content-Type": "application/json",
                  },
                  body: JSON.stringify({
                    mobile_phone: mobile_phone,
                    region_code: region_code,
                    new_password: encryptedPassword,
                    ...base,
                  }),
                }
              );
              const newData = await response.json();
              console.log("base", base);
              if (newData.ret === -1) {
                Toast.show({
                  type: "error",
                  text1: newData.msg,
                  topOffset: 60,
                });
                return;
              }
              signIn(data, mobilePhone, region_code);
            } catch (error) {
              console.error(error);
            }
          }}
        >
          {({ handleChange, handleSubmit, values }) => (
            <View style={tailwind("flex px-10 mt-32  justify-center")}>
              <Text style={tailwind("text-3xl text-white font-medium")}>
                设置密码
              </Text>
              <Text style={tailwind("text-base text-white mb-10")}>
                请牢记密码
              </Text>
              <View
                style={tailwind("border-2 border-[#2c2b2f] rounded-2xl p-4")}
              >
                <View
                  style={tailwind("flex flex-row flex-nowrap items-center")}
                >
                  <Text style={tailwind("text-base text-white mr-4")}>
                    密码
                  </Text>
                  <TextInput
                    placeholder="请输入8-15位密码"
                    placeholderTextColor="#FFFFFF80"
                    underlineColorAndroid="transparent"
                    secureTextEntry={true}
                    onChangeText={handleChange("password")}
                    value={values.password}
                    style={tailwind("flex-1 text-white")}
                  />
                </View>
                <View style={tailwind("my-4")}>
                  <MyDivider />
                </View>
                <View
                  style={tailwind("flex flex-row flex-nowrap items-center")}
                >
                  <Text style={tailwind("text-base text-white mr-4")}>
                    确认密码
                  </Text>
                  <TextInput
                    placeholder="请再次确认密码"
                    placeholderTextColor="#FFFFFF80"
                    underlineColorAndroid="transparent"
                    secureTextEntry={true}
                    onChangeText={handleChange("confirm_password")}
                    value={values.confirm_password}
                    style={tailwind("flex-1 text-white")}
                  />
                </View>
              </View>
              <Button
                color="#FF669E"
                radius="999"
                size="md"
                onPress={handleSubmit}
                titleStyle={tailwind("text-base font-medium")}
                containerStyle={tailwind("mt-16")}
              >
                登录
              </Button>
              <Text
                onPress={() => signIn(data, mobilePhone, region_code)}
                style={tailwind("text-base text-center text-[#FFFFFF80] mt-4")}
              >
                跳过
              </Text>
            </View>
          )}
        </Formik>
      </ScrollView>
    </TouchableWithoutFeedback>
  );
}
