import {
  View,
  Text,
  Image as NativeImage,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { get } from "../../../utils/storeInfo";
import { Icon } from "@rneui/themed";
import UpdateModal from "../../../components/UpdateModal";
import baseRequest from "../../../utils/baseRequest";
import Toast from "react-native-toast-message";
import { generateSignature } from "../../../utils/crypto";

export default function AboutUs({ navigation }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  const [version, setVersion] = useState("");
  //获取当前版本信息
  useEffect(() => {
    const getVersion = async () => {
      const appInfo = await get("app_info");
      setVersion(appInfo?.b_ver);
    };
    getVersion();
  }, []);

  //控制更新弹窗出现
  const [isUpdateModalVisible, setIsUpdateModalVisible] = useState(false);
  //保存最新版本信息
  const [versionData, setVersionData] = useState({});
  //检查更新
  async function checkUpdate() {
    try {
      const base = await baseRequest();
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const signature = await generateSignature({
        ...base,
      });
      //检查更新
      const checkUpdataResponse = await fetch(
        `${apiUrl}/api/version/is_there_a_new_version_available?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
          }),
        }
      );
      const checkUpdataData = await checkUpdataResponse.json();
      if (checkUpdataData.ret === -1) {
        return;
      }
      if (!checkUpdataData.data.result) {
        Toast.show({
          type: "success",
          text1: "当前已是最新版本",
          topOffset: 60,
        });
        return;
      }
      if (checkUpdataData.data.result) {
        setIsUpdateModalVisible(true);
        setVersionData(checkUpdataData.data);
      }
    } catch (e) {
      console.warn(e);
    }
  }

  return (
    <ScrollView
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("flex justify-center items-center mt-14")}>
        <NativeImage
          source={require("../../../assets/icon/others/icon_border.png")}
        />
        <Text style={tailwind("text-white text-base font-medium mt-4")}>
          V {version}
        </Text>
      </View>
      <View
        style={{
          ...tailwind("flex flex-col py-2 rounded-2xl mt-14 border-2 mx-4"),
          borderColor: "#2c2b2f",
        }}
      >
        <TouchableOpacity
          onPress={() =>
            navigation.navigate("WebWithHeader", {
              title: "用户协议",
              uri: `${process.env.EXPO_PUBLIC_WEB_URL}/doc/useragreement`,
            })
          }
          style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
        >
          <Icon name="document-text-outline" type="ionicon" color="white" />
          <Text style={tailwind("text-base text-white ml-2 flex-1")}>
            用户协议
          </Text>
          <NativeImage
            source={require("../../../assets/icon/32DP/smalllink.png")}
          />
        </TouchableOpacity>
        <TouchableOpacity
          onPress={checkUpdate}
          style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
        >
          <Icon name="refresh-outline" type="ionicon" color="white" />
          <Text style={tailwind("text-base text-white ml-2 flex-1")}>
            检查更新
          </Text>
          <NativeImage
            source={require("../../../assets/icon/32DP/smalllink.png")}
          />
        </TouchableOpacity>
      </View>
      <UpdateModal
        visible={isUpdateModalVisible}
        setVisible={setIsUpdateModalVisible}
        data={versionData}
      />
    </ScrollView>
  );
}
