import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, StyleSheet, Image, Platform } from "react-native";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "../App";
import MyStatusbar from "./component/MyStatusbar";
import MyHeader from "./component/MyHeader";
import UpdateModal from "./component/UpdateModal";
import pxToDp from "./helper/pxToDp";
import DeviceInfo from "react-native-device-info";
import { useTranslation } from "react-i18next";

type Props = NativeStackScreenProps<RootStackParamList>;

interface UpdateInfo {
  latestVersion: string;
  downloadUrl: string;
  updateLogs: string[];
}

const UPDATE_JSON_URL = `https://powerfun.oss-cn-shanghai.aliyuncs.com/yecongdfu/apks/update.json?t=${Date.now()}`;

const compareVersions = (latest: string, current: string): boolean => {
  const latestParts = latest.split(".").map(Number);
  const currentParts = current.split(".").map(Number);

  for (let i = 0; i < Math.max(latestParts.length, currentParts.length); i++) {
    const latestNum = latestParts[i] || 0;
    const currentNum = currentParts[i] || 0;
    if (latestNum > currentNum) return true;
    if (latestNum < currentNum) return false;
  }
  return false;
};

export default function HomeScreen({ navigation }: Props) {
  const { t } = useTranslation();
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
  const [currentVersion, setCurrentVersion] = useState("");

  useEffect(() => {
    const checkUpdate = async () => {
      try {
        const version = DeviceInfo.getVersion();
        setCurrentVersion(version);

        const resp = await fetch(UPDATE_JSON_URL);
        if (!resp.ok) return;

        const data = await resp.json();
        const platform = Platform.OS === "ios" ? "ios" : "android";
        const platformUpdate = data[platform];
        if (!platformUpdate) return;

        if (compareVersions(platformUpdate.latestVersion, version)) {
          setUpdateInfo({
            latestVersion: platformUpdate.latestVersion,
            downloadUrl: platformUpdate.downloadUrl,
            updateLogs: platformUpdate.updateLogs || [],
          });
          setUpdateModalVisible(true);
        }
      } catch (e) {
        console.log("检查更新失败:", e);
      }
    };

    checkUpdate();
  }, []);

  return (
    <View style={styles.container}>
      <MyStatusbar backgroundColor="#E7141E" dark={false}></MyStatusbar>
      <MyHeader
        title={t("home.title")}
        textColor="#fff"
        backgroundColor="#E7141E"
        hideBack
        navigation={navigation}
        rightView={
          <TouchableOpacity
            style={{ width: pxToDp(56), height: pxToDp(56), alignItems: "center", justifyContent: "center" }}
            onPress={() => navigation.navigate("Setting")}
          >
            <Image source={require("./img/Settings.png")} style={{ width: pxToDp(48), height: pxToDp(44) }}></Image>
          </TouchableOpacity>
        }
      ></MyHeader>

      <View style={styles.centerBox}>
        <Image source={require("./img/Search.png")} style={{ width: pxToDp(568), height: pxToDp(344), marginBottom: pxToDp(100) }}></Image>
        <TouchableOpacity style={styles.button} onPress={() => navigation.navigate("Scan")}>
          <Text style={styles.buttonText}>{t("home.powerMeter")}</Text>
        </TouchableOpacity>
        <TouchableOpacity style={[styles.button, { marginTop: pxToDp(20) }]} onPress={() => navigation.navigate("ScanScreen2")}>
          <Text style={styles.buttonText}>{t("home.paddle")}</Text>
        </TouchableOpacity>
        {/* <TouchableOpacity style={[styles.button, { marginTop: pxToDp(20) }]} onPress={() => navigation.navigate("ScanScreen3")}>
          <Text style={styles.buttonText}>{t("home.T5trainer")}</Text>
        </TouchableOpacity> */}
      </View>

      <UpdateModal
        visible={updateModalVisible}
        updateInfo={updateInfo}
        currentVersion={currentVersion}
        onClose={() => setUpdateModalVisible(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  centerBox: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "#fff",
    paddingTop: pxToDp(250),
  },
  button: {
    backgroundColor: "#E7141E",
    borderRadius: pxToDp(24),
    width: pxToDp(300),
    height: pxToDp(96),
    alignItems: "center",
    justifyContent: "center",
  },
  buttonText: {
    color: "#fff",
    fontSize: pxToDp(32),
    fontWeight: "bold",
  },
  bottomBox: {
    alignItems: "center",
    marginBottom: 20,
  },
  privacyText: {
    fontSize: 16,
    color: "#E7141E",
    marginBottom: 8,
  },
  version: {
    fontSize: 14,
    color: "#999",
  },
});
