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";
import { BRAND_NAME, THEME } from "./theme";

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={THEME.background} dark={false}></MyStatusbar>
      <MyHeader
        title={t("home.title")}
        textColor={THEME.text}
        backgroundColor={THEME.background}
        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), tintColor: THEME.text }}
            ></Image>
          </TouchableOpacity>
        }
      ></MyHeader>

      <View style={styles.centerBox}>
        <Image source={require("../assets/logo.png")} style={styles.logo}></Image>
        <Text style={styles.brandName}>{BRAND_NAME}</Text>
        <Text style={styles.subtitle}>{t("home.subtitle")}</Text>
        <TouchableOpacity style={styles.button} onPress={() => navigation.navigate("Scan")}>
          <Text style={styles.buttonText}>{t("home.powerMeter")}</Text>
        </TouchableOpacity>
        <Text style={styles.version}>{t("home.versionPrefix")} {currentVersion || DeviceInfo.getVersion()}</Text>
      </View>

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: THEME.background,
  },
  centerBox: {
    flex: 1,
    alignItems: "center",
    backgroundColor: THEME.background,
    paddingTop: pxToDp(160),
    paddingHorizontal: pxToDp(48),
  },
  logo: {
    width: pxToDp(320),
    height: pxToDp(320),
    marginBottom: pxToDp(36),
  },
  brandName: {
    color: THEME.text,
    fontSize: pxToDp(42),
    fontWeight: "800",
    letterSpacing: 3,
    marginBottom: pxToDp(12),
    textAlign: "center",
  },
  subtitle: {
    color: THEME.textMuted,
    fontSize: pxToDp(26),
    marginBottom: pxToDp(72),
    textAlign: "center",
  },
  button: {
    backgroundColor: THEME.text,
    borderRadius: pxToDp(24),
    width: pxToDp(360),
    height: pxToDp(96),
    alignItems: "center",
    justifyContent: "center",
  },
  buttonText: {
    color: THEME.background,
    fontSize: pxToDp(32),
    fontWeight: "bold",
    letterSpacing: 1,
  },
  version: {
    fontSize: pxToDp(24),
    color: THEME.textMuted,
    marginTop: pxToDp(28),
  },
});
