import { Ionicons } from "@expo/vector-icons";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    ActivityIndicator,
    Alert,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from "react-native";
import services from "../../services/api";

export default function WithdrawScreen() {
  const router = useRouter();
  const params = useLocalSearchParams();
  const [balance, setBalance] = useState("0.00");
  const [money, setMoney] = useState("");
  const [bankInfo, setBankInfo] = useState<any>(null);
  const [rate, setRate] = useState(0);
  const [agree, setAgree] = useState(false);
  const [loading, setLoading] = useState(false);

  // Uniapp had type='ALIPAY' default
  const type = (params.type as string) || "ALIPAY";

  useEffect(() => {
    fetchData();
    fetchRate();
    fetchWithdrawInfo();
  }, []);

  const fetchData = async () => {
    try {
      const res = await services.purse.withdrawPre(type, "MAGIC_PROMOTION");
      if (res && res.avaliableWithdraw) {
        setBalance(res.avaliableWithdraw.amount);
      }
    } catch (error) {
      console.error("Fetch withdraw pre failed", error);
    }
  };

  const fetchRate = async () => {
    try {
      await services.user
        .getParamConfig("wallet_withdraw_rate")
        .then((res: any) => {
          setRate(res.data ? Number(res.data) : 0);
        });
    } catch (error) {
      console.error("Fetch rate failed", error);
    }
  };

  const fetchWithdrawInfo = async () => {
    try {
      const res = await services.purse.getWithdraw();
      setBankInfo(res);
    } catch (error) {
      console.error("Fetch bank info failed", error);
    }
  };

  const handleWithdraw = async () => {
    if (!agree) {
      Alert.alert("提示", "请您先阅读并同意提现协议");
      return;
    }
    if (!bankInfo || !bankInfo.bankNum) {
      Alert.alert("提示", "请新增银行卡信息");
      return;
    }
    const amount = parseFloat(money);
    if (
      !money ||
      isNaN(amount) ||
      amount <= 0 ||
      amount > parseFloat(balance)
    ) {
      Alert.alert("提示", "请输入正确的金额");
      return;
    }

    setLoading(true);
    try {
      const success = await services.purse.withdraw({
        money,
        ...bankInfo,
        walletType: "MAGIC_PROMOTION",
        accountType: "3",
      });
      if (success) {
        Alert.alert("成功", "提现申请已提交", [
          {
            text: "确定",
            onPress: () => router.push("/wallet/withdraw_record"),
          },
        ]);
        setMoney("");
      }
    } catch (error) {
      console.error("Withdraw failed", error);
    } finally {
      setLoading(false);
    }
  };

  const realMoney = money
    ? (parseFloat(money) * (1 - rate)).toFixed(2)
    : "0.00";

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

      <View style={styles.groupContainer}>
        {/* Bank Card Section */}
        <TouchableOpacity
          style={styles.formGroup}
          onPress={() => router.push("/cardInfo")}
        >
          <Text style={styles.label}>提现至</Text>
          <View style={styles.rightContent}>
            <Text style={styles.valueText}>
              {bankInfo && bankInfo.bankName
                ? `${bankInfo.bankName}尾号(${bankInfo.bankNum.slice(-4)})`
                : "暂无银行卡信息"}
            </Text>
            <Ionicons name="chevron-forward" size={16} color="#8799a3" />
          </View>
        </TouchableOpacity>
      </View>

      <View style={styles.groupContainer}>
        <View style={styles.formGroup}>
          <Text style={styles.label}>可提现金额:{balance}元</Text>
          <TouchableOpacity style={styles.ruleBtn}>
            <Ionicons name="help-circle" size={16} color="#5b5b5b" />
            <Text style={styles.ruleText}>提现规则</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.formGroupInput}>
          <Text style={styles.currencySymbol}>￥</Text>
          <TextInput
            style={styles.input}
            value={money}
            onChangeText={setMoney}
            keyboardType="decimal-pad"
            placeholder="请输入提现金额"
          />
          <TouchableOpacity onPress={() => setMoney(balance)}>
            <Text style={styles.withdrawAll}>全部提现</Text>
          </TouchableOpacity>
        </View>

        <View style={[styles.formGroup, { backgroundColor: "#f8f8f8" }]}>
          <Text style={styles.label}>税率：</Text>
          <Text style={styles.valueText}>{(rate * 100).toFixed(0)}%</Text>
        </View>
        <View style={[styles.formGroup, { backgroundColor: "#f8f8f8" }]}>
          <Text style={styles.label}>实际到账金额：</Text>
          <Text style={styles.valueText}>{realMoney}</Text>
        </View>
      </View>

      <TouchableOpacity
        style={styles.recordLink}
        onPress={() => router.push("/wallet/withdraw_record")}
      >
        <Text style={styles.recordLinkText}>提现记录</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.agreement}
        onPress={() => setAgree(!agree)}
      >
        <Ionicons
          name={agree ? "radio-button-on" : "radio-button-off"}
          size={20}
          color={agree ? "#8b3dff" : "#8799a3"}
        />
        <Text style={styles.agreementText}>
          我已阅读并同意 <Text style={styles.linkText}>《提现协议》</Text>
        </Text>
      </TouchableOpacity>

      <View style={styles.footer}>
        <TouchableOpacity
          style={[styles.confirmBtn, loading && styles.disabledBtn]}
          onPress={handleWithdraw}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.confirmBtnText}>确认提现</Text>
          )}
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  groupContainer: {
    paddingHorizontal: 12,
    paddingTop: 18,
  },
  formGroup: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 15,
    backgroundColor: "#fff",
    // borderBottomWidth: 1,
    // borderBottomColor: '#eee',
  },
  formGroupInput: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
  },
  label: {
    fontSize: 15,
    color: "#333",
  },
  rightContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  valueText: {
    fontSize: 15,
    color: "#666",
    marginRight: 5,
  },
  ruleBtn: {
    flexDirection: "row",
    alignItems: "center",
  },
  ruleText: {
    fontSize: 14,
    color: "#5b5b5b",
    marginLeft: 4,
  },
  currencySymbol: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#333",
    width: 30,
  },
  input: {
    flex: 1,
    fontSize: 20,
    paddingHorizontal: 10,
  },
  withdrawAll: {
    color: "#ff9600",
    fontSize: 14,
  },
  recordLink: {
    alignItems: "center",
    marginTop: 18,
  },
  recordLinkText: {
    fontSize: 12,
    color: "#999",
  },
  agreement: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    marginTop: 20,
  },
  agreementText: {
    fontSize: 12,
    color: "#333",
    marginLeft: 4,
  },
  linkText: {
    color: "#8b3dff",
  },
  footer: {
    paddingHorizontal: 26,
    paddingTop: 6,
    marginTop: 20,
    backgroundColor: "#f6f6f6", // Optional visual separation if needed, or transparent
    paddingBottom: 40,
  },
  confirmBtn: {
    backgroundColor: "#8b3dff", // Theme color
    height: 50,
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
  },
  disabledBtn: {
    opacity: 0.7,
  },
  confirmBtnText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "bold",
  },
});
