import { View, Text, Modal, TouchableOpacity } from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { Button } from "@rneui/themed";
import Toast from "react-native-toast-message";
import baseRequest from "../../utils/baseRequest";
import { generateSignature } from "../../utils/crypto";
import { get } from "../../utils/storeInfo";
import { useNavigation } from "@react-navigation/native";

export default function CoinPayModal({
  visible,
  setVisible,
  url,
  body = {},
  product,
  coinPrice,
  validity,
  info,
  onPurchaseDone = () => {},
}) {
  const tailwind = useTailwind();
  const navigation = useNavigation();
  const apiUrl = process.env.EXPO_PUBLIC_API_URL;

  //用户金币余额
  const [coinBalance, setCoinBalance] = useState();
  useEffect(() => {
    if (!visible) {
      setIsCoinEnough(true);
      setIsWaitingConfirm(false);
      return;
    }
    const init = async () => {
      const base = await baseRequest();
      const account = await get("account");
      const body = {
        ...base,
        mid: account.mid,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/account/list_by_mid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      setCoinBalance(_data.data.account.gold_num);
    };
    init();
  }, [visible]);

  //判断余额是否充足
  const [isCoinEnough, setIsCoinEnough] = useState(true);
  const [isWaitingConfirm, setIsWaitingConfirm] = useState(false);
  const checkCoinBalance = async () => {
    if (coinBalance < coinPrice) {
      setIsCoinEnough(false);
      return;
    }
    setIsWaitingConfirm(true);
  };

  //进行金币支付
  const handleCoinPay = async () => {
    try {
      const base = await baseRequest();
      const _body = {
        ...base,
        ...body,
        pay_type: "coin",
        from: "app",
      };
      const signature = await generateSignature(_body);
      const _response = await fetch(`${apiUrl + url}?signature=${signature}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(_body),
      });
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      setVisible(false);
      onPurchaseDone();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Modal
      visible={visible}
      transparent={true}
      statusBarTranslucent
      animationType="fade"
    >
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => setVisible(false)}
        style={{
          backgroundColor: "#00000080",
          ...tailwind("flex-1 justify-center items-center"),
        }}
      >
        <TouchableOpacity
          activeOpacity={1}
          style={tailwind("p-4 rounded-2xl bg-[#17161A] items-center w-3/4")}
        >
          <View style={tailwind("flex flex-col w-full px-4")}>
            {isCoinEnough ? (
              isWaitingConfirm ? (
                <>
                  <Text
                    style={tailwind(
                      "text-white text-xl font-semibold text-center mt-2"
                    )}
                  >
                    本次消费将扣除您{coinPrice}金币，是否确认购买？
                  </Text>
                  <Text style={tailwind("text-white text-sm text-center mt-2")}>
                    当前余额：{coinBalance}金币
                  </Text>
                </>
              ) : (
                <>
                  <Text
                    style={tailwind("text-white text-xl font-semibold mt-2")}
                  >
                    项目：{product}
                  </Text>
                  <Text
                    style={tailwind("text-white text-xl font-semibold mt-2")}
                  >
                    价格：{coinPrice}金币
                  </Text>
                  <Text style={tailwind("text-[#FFFFFF80] text-sm mt-2")}>
                    （ 1 RMB = 10 金币 ）
                  </Text>
                  {validity && (
                    <Text
                      style={tailwind("text-white text-xl font-semibold mt-2")}
                    >
                      有效期：{validity}
                    </Text>
                  )}
                  {info && (
                    <Text style={tailwind("text-[#FFFFFF80] text-sm mt-2")}>
                      {info}
                    </Text>
                  )}
                </>
              )
            ) : (
              <>
                <Text
                  style={tailwind(
                    "text-white text-xl font-semibold text-center mt-2"
                  )}
                >
                  余额不足，请先充值金币
                </Text>
                <Text style={tailwind("text-white text-sm text-center mt-2")}>
                  当前余额：{coinBalance}金币
                </Text>
              </>
            )}
            {!isWaitingConfirm && isCoinEnough && (
              <Button
                onPress={checkCoinBalance}
                color="#FF669E"
                radius="999"
                size="md"
                titleStyle={tailwind("text-base")}
                containerStyle={tailwind("w-full mt-4")}
              >
                购买
              </Button>
            )}
            {isWaitingConfirm && (
              <Button
                onPress={handleCoinPay}
                color="#FF669E"
                radius="999"
                size="md"
                titleStyle={tailwind("text-base")}
                containerStyle={tailwind("w-full mt-4")}
              >
                确认
              </Button>
            )}
            {!isCoinEnough && (
              <Button
                onPress={() => {
                  navigation.navigate("Wallet");
                  setVisible(false);
                  setIsCoinEnough(true);
                }}
                color="#FF669E"
                radius="999"
                size="md"
                titleStyle={tailwind("text-base")}
                containerStyle={tailwind("w-full mt-4")}
              >
                前往充值
              </Button>
            )}
            <TouchableOpacity
              onPress={() => setVisible(false)}
              style={tailwind("mt-4")}
            >
              <Text
                style={tailwind(
                  "text-[#FFFFFF80] text-base font-medium text-center"
                )}
              >
                取消
              </Text>
            </TouchableOpacity>
          </View>
        </TouchableOpacity>
      </TouchableOpacity>
    </Modal>
  );
}
