import {
  View,
  Text,
  Modal,
  TouchableOpacity,
  Platform,
  Image,
  ActivityIndicator,
} from "react-native";
import React, { useState } from "react";
import { useTailwind } from "tailwind-rn";
import { Button } from "@rneui/themed";
import * as Linking from "expo-linking";
import * as FileSystem from "expo-file-system";
import * as IntentLauncher from "expo-intent-launcher";
import Toast from "react-native-toast-message";

export default function UpdateModal({ visible, setVisible, data }) {
  const tailwind = useTailwind();

  const [isInstalling, setIsInstalling] = useState(false);

  //安卓下载安装最新安装包
  const downloadAndInstallAPK = async () => {
    setIsInstalling(true);
    const apkUrl = data.download_url;

    try {
      const downloadResumable = FileSystem.createDownloadResumable(
        apkUrl,
        `${FileSystem.documentDirectory}ironfans.apk`
      );

      const { uri } = await downloadResumable.downloadAsync();
      const localUri = await FileSystem.getContentUriAsync(uri);

      await IntentLauncher.startActivityAsync(
        "android.intent.action.INSTALL_PACKAGE",
        {
          data: localUri,
          flags: 1,
        }
      );
    } catch (error) {
      Toast.show({
        type: "error",
        text1: "安装失败，请前往官网下载" + error,
        topOffset: 60,
      });
    } finally {
      setIsInstalling(false);
    }
  };

  return (
    <Modal
      visible={visible}
      transparent={true}
      statusBarTranslucent
      animationType="fade"
    >
      <TouchableOpacity
        activeOpacity={1}
        style={{
          backgroundColor: "#00000080",
          ...tailwind("flex-1 justify-center items-center"),
        }}
      >
        <TouchableOpacity
          activeOpacity={1}
          style={tailwind("p-4 rounded-2xl bg-[#1E1C29] items-center w-3/4")}
        >
          <View style={tailwind("flex flex-col w-full")}>
            <Image source={require("../../assets/icon/others/slogan.png")} />
            <Text
              style={tailwind(
                "text-white text-xl font-semibold text-center mt-2"
              )}
            >
              发现新版本
              {data?.version}
            </Text>
            <Text
              style={tailwind("text-[#FFFFFF80] text-sm font-medium mt-2 mb-4")}
            >
              {data?.log}
            </Text>
            <Button
              onPress={
                Platform.OS === "ios"
                  ? () => Linking.openURL(data?.download_url)
                  : () => downloadAndInstallAPK()
              }
              color="#FF669E"
              radius="999"
              size="md"
              disabled={isInstalling}
              disabledStyle={tailwind("bg-[#FFFFFF80]")}
              disabledTitleStyle={tailwind("text-white")}
              titleStyle={tailwind("text-base")}
              containerStyle={tailwind("w-full px-4")}
            >
              {isInstalling && <ActivityIndicator size="small" color="white" />}
              {isInstalling ? "正在下载..." : "立即更新"}
            </Button>
            {!data?.force && (
              <TouchableOpacity
                onPress={() => setVisible(false)}
                style={tailwind("my-4")}
              >
                <Text
                  style={tailwind(
                    "text-[#FFFFFF80] text-base font-medium text-center"
                  )}
                >
                  暂不更新
                </Text>
              </TouchableOpacity>
            )}
          </View>
        </TouchableOpacity>
      </TouchableOpacity>
    </Modal>
  );
}
