import Alipay from "expo-native-alipay";
import { Stack, useRouter } from "expo-router";
import React, { useState } from "react";
import {
    ActivityIndicator,
    Alert,
    AppState,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from "react-native";
import services from "../../services/api";

const MAX_AMOUNT = 100000;

export default function RechargeScreen() {
  const router = useRouter();
  const [money, setMoney] = useState("");
  const [loading, setLoading] = useState(false);

  const validateInput = (text: string) => {
    let value = text
      .replace(/[^\d.]/g, "")
      .replace(/^\./g, "")
      .replace(/\.{2,}/g, ".");

    value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3");

    if (parseFloat(value) > MAX_AMOUNT) {
      Alert.alert("提示", `最大充值金额为${MAX_AMOUNT}元`);
      value = MAX_AMOUNT.toString();
    }
    setMoney(value);
  };

  const handleRecharge = async () => {
    const amount = parseFloat(money);
    if (!amount || amount <= 0) {
      Alert.alert("提示", "请输入有效的充值金额");
      return;
    }

    setLoading(true);
    setLoading(true);
    try {
      // Use ALIPAY_APP for native payment with correct API
      const res: any = await services.purse.rechargeSubmit(
        amount,
        "ALIPAY_APP",
        "CASH",
      );

      console.log("Recharge API Res:", res);

      // Handle response which might be direct string or object with payInfo
      const payInfo =
        typeof res?.data === "string"
          ? res?.data
          : res?.data?.payInfo || res?.data?.orderInfo || res?.data?.tradeNo;

      if (
        payInfo &&
        typeof payInfo === "string" &&
        (payInfo.startsWith("alipay_root_cert_sn") ||
          payInfo.includes("alipay_sdk"))
      ) {
        let appStateSub: any = null;
        let isResolved = false;

        try {
          Alipay.setAlipayScheme("alipay2021005175632205");

          appStateSub = AppState.addEventListener(
            "change",
            async (nextAppState) => {
              if (nextAppState === "active" && !isResolved) {
                setTimeout(async () => {
                  if (!isResolved) {
                    console.log(
                      "Alipay SDK did not resolve natively, assuming success to refresh...",
                    );
                    isResolved = true;
                    Alert.alert("提示", "充值已发起，请稍后查看余额");
                    router.replace("/wallet/recharge_record");
                  }
                }, 500); // 0.5秒后提示充值已发起
              }
            },
          );

          const result = await Alipay.pay(payInfo);
          if (isResolved) return;
          isResolved = true;
          console.log("Alipay Result:", result);

          if (result?.resultStatus === "9000") {
            Alert.alert("提示", "充值成功");
            router.replace("/wallet/recharge_record");
          } else if (result?.resultStatus === "6001") {
            Alert.alert("提示", "用户取消支付");
          } else {
            Alert.alert("提示", "支付未完成");
          }
        } catch (e: any) {
          isResolved = true;
          Alert.alert("提示", "调用支付宝失败: " + (e.message || ""));
        } finally {
          if (appStateSub) {
            appStateSub.remove();
          }
        }
      } else if (res?.data?.tradeNo && !payInfo) {
        Alert.alert("提示", "获取支付信息失败(仅获取到订单号)");
      } else {
        Alert.alert("失败", "生成充值订单失败 " + (res?.msg || ""));
      }
    } catch (error) {
      console.error("Recharge failed", error);
      Alert.alert("错误", "充值失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Stack.Screen
        options={{
          title: "充值",
          headerStyle: { backgroundColor: "#fff" },
          headerShadowVisible: false,
        }}
      />

      <View style={styles.content}>
        <View style={styles.inputWrapper}>
          <Text style={styles.label}>充值金额:</Text>
          <TextInput
            style={styles.input}
            value={money}
            onChangeText={validateInput}
            placeholder="请输入金额"
            keyboardType="decimal-pad"
          />
        </View>

        <Text style={styles.tip}>充值金额可以用于购买手办，奖池</Text>
        <Text style={styles.tipSub}>
          充值金额不可提现，
          <Text style={styles.highlight}>线下充值额外返10%</Text>
        </Text>

        <TouchableOpacity
          style={[styles.btn, loading && styles.disabledBtn]}
          onPress={handleRecharge}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.btnText}>充值</Text>
          )}
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.recordLink}
          onPress={() => router.push("/wallet/recharge_record")}
        >
          <Text style={styles.recordLinkText}>
            充值记录 {">"}
            {">"}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  content: {
    paddingHorizontal: 24,
    paddingTop: 32,
  },
  inputWrapper: {
    flexDirection: "row",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 8,
    paddingHorizontal: 16,
    height: 52, // 104rpx
    marginTop: 15,
  },
  label: {
    fontSize: 16, // font5
    color: "#333",
    marginRight: 10,
  },
  input: {
    flex: 1,
    fontSize: 16, // font5
    height: "100%",
  },
  tip: {
    textAlign: "center",
    color: "#666", // color-2
    fontSize: 14,
    marginTop: 36,
  },
  tipSub: {
    textAlign: "center",
    color: "#666", // color-2
    fontSize: 14,
    marginTop: 5,
    marginBottom: 20,
  },
  highlight: {
    color: "#07C160",
    textDecorationLine: "underline",
  },
  btn: {
    backgroundColor: "#0081ff", // bg-blue
    height: 44,
    borderRadius: 4,
    justifyContent: "center",
    alignItems: "center",
    width: "70%",
    alignSelf: "center",
  },
  disabledBtn: {
    opacity: 0.7,
  },
  btnText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "bold",
  },
  recordLink: {
    marginTop: 20,
    alignItems: "center",
  },
  recordLinkText: {
    color: "#8b3dff", // color-theme
    fontSize: 14,
  },
});
