import { View, TextInput } from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "@rneui/themed";
import Toast from "react-native-toast-message";
import baseRequest from "../../../utils/baseRequest";
import { get, save } from "../../../utils/storeInfo";
import { generateSignature } from "../../../utils/crypto";

export default function EditUserName({ navigation }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [oldName, setOldName] = useState();
  const [name, setName] = useState();

  useEffect(() => {
    const getName = async () => {
      const account = await get("account");
      setName(account.name);
      setOldName(account.name);
    };
    getName();
  }, []);

  const handleSubmit = async () => {
    if (!name) {
      Toast.show({
        type: "error",
        text1: "昵称不得为空",
        topOffset: 60,
      });
      return;
    } else if (name.length > 10) {
      Toast.show({
        type: "error",
        text1: "昵称不得超过10个字",
        topOffset: 60,
      });
      return;
    } else if (name === oldName) {
      navigation.goBack();
      return;
    }
    //获取环境变量
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;

    const base = await baseRequest();
    const account = await get("account");
    const signature = await generateSignature({
      ...base,
      name: name,
      mid: account.mid,
    });
    try {
      const response = await fetch(
        `${apiUrl}/api/account/update?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            name: name,
            mid: account.mid,
          }),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          type: "error",
          text1: data.msg,
          topOffset: 60,
        });
        return;
      }
      //向服务器请求新的账号信息并保存到本地
      const signature2 = await generateSignature({
        ...base,
        mid: account.mid,
      });
      const accountResponse = await fetch(
        `${apiUrl}/api/account/list_by_mid?signature=${signature2}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            mid: account.mid,
          }),
        }
      );
      const accountData = await accountResponse.json();
      if (accountData.ret === -1) {
        Toast.show({
          type: "error",
          text1: accountData.msg,
          topOffset: 60,
        });
        return;
      }
      await save("account", accountData.data.account);
    } catch (error) {
      console.error(error);
    }
    navigation.goBack();
  };

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("p-4")}>
        <TextInput
          placeholder="请输入新昵称"
          placeholderTextColor="#FFFFFF80"
          underlineColorAndroid="transparent"
          maxLength={8}
          onChangeText={(value) => setName(value)}
          value={name}
          style={tailwind(
            "flex rounded-full bg-[#FFFFFF1A] text-white h-12 px-4"
          )}
        />
        <Button
          color="#FF669E"
          radius="999"
          size="md"
          containerStyle={tailwind("mt-16")}
          onPress={handleSubmit}
        >
          确认
        </Button>
      </View>
    </View>
  );
}
