import { View, Text, Image, TouchableOpacity } from "react-native";
import React, { useState, useCallback } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Divider, Icon } from "@rneui/themed";
import { LinearGradient } from "expo-linear-gradient";
import { useHeaderHeight } from "@react-navigation/elements";
import { get, save } from "../../utils/storeInfo";
import baseRequest from "../../utils/baseRequest";
import Toast from "react-native-toast-message";
import * as Linking from "expo-linking";
import { generateSignature } from "../../utils/crypto";
import { useFocusEffect } from "@react-navigation/native";

export default function Wallet({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const headerHeight = useHeaderHeight();

  const [tokenAndMobilePhone, setTokenAndMobilePhone] = useState("");
  const [data, setData] = useState("");
  //每次focus都更新一次数据
  useFocusEffect(
    useCallback(() => {
      const getData = async () => {
        //获取环境变量
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const account = await get("account");
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
          mid: account.mid,
        });
        try {
          //获取账号基本信息
          const accountResponse = await fetch(
            `${apiUrl}/api/account/list_by_mid?signature=${signature}`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                ...base,
                mid: account.mid,
              }),
            }
          );
          const accountData = await accountResponse.json();
          if (accountData.ret === -1) {
            Toast.show({
              type: "error",
              text1: accountData.msg,
              topOffset: 60,
            });
            return;
          }
          await save("account", accountData.data.account);
          setData(accountData.data.account);
          const tokenCache = await get("token");
          const temToken = encodeURIComponent(tokenCache);
          const mobilePhone = await get("mobile_phone");
          setTokenAndMobilePhone({
            token: temToken,
            mobile_phone: mobilePhone,
          });
        } catch (error) {
          console.error(error);
        }
      };
      getData();
    }, [])
  );

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <LinearGradient
        colors={["#FF669E", "#07050A"]}
        start={[0, 0]} // 渐变起点坐标
        end={[0, 1]} // 渐变终点坐标
        style={{ ...tailwind("px-4 pb-32"), paddingTop: headerHeight }}
      >
        <View style={tailwind("flex flex-row justify-around mt-2 w-full")}>
          <View style={tailwind("flex flex-col items-center w-1/4")}>
            <Image
              source={require("../../assets/images/icon_goldcoin.png")}
              style={tailwind("w-12 h-12")}
            />
            <Text style={tailwind("text-2xl font-semibold text-white")}>
              {data?.gold_num}
            </Text>
            <Text style={tailwind("text-sm text-white")}>金币</Text>
          </View>
          {data?.role === 3 && <Divider orientation="vertical" width={1} />}
          {data?.role === 3 && (
            <View style={tailwind("flex flex-col items-center w-1/4")}>
              <Image
                source={require("../../assets/images/icon_diamond.png")}
                style={tailwind("w-12 h-12")}
              />
              <Text style={tailwind("text-2xl font-semibold text-white")}>
                {data?.diamond_num}
              </Text>
              <Text style={tailwind("text-sm text-white")}>钻石</Text>
            </View>
          )}
        </View>
      </LinearGradient>
      <View style={tailwind("relative px-4")}>
        <View
          style={tailwind(
            "absolute -top-24 left-4 w-full rounded-2xl px-4 bg-[#13121F]"
          )}
        >
          <TouchableOpacity
            onPress={() =>
              navigation.navigate("WebWithHeader", {
                title: "充值中心",
                uri: process.env.EXPO_PUBLIC_WEB_URL + "/pay",
              })
            }
            style={tailwind("flex-row justify-between items-center py-4")}
          >
            <View style={tailwind("flex-row items-center")}>
              <Icon type="ionicon" name="card-outline" size={32} color="red" />
              <Text style={tailwind("text-base text-white font-medium ml-2")}>
                充值
              </Text>
            </View>
            <Icon
              type="ionicon"
              name="chevron-forward-outline"
              size={28}
              color="white"
            />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() =>
              navigation.navigate("WebWithHeader", {
                title: "收支明细",
                uri: process.env.EXPO_PUBLIC_WEB_URL + "/bill/cost",
              })
            }
            style={tailwind("flex-row justify-between items-center py-4")}
          >
            <View style={tailwind("flex-row items-center")}>
              <Icon type="ionicon" name="print" size={32} color="#60a5fa" />
              <Text style={tailwind("text-base text-white font-medium ml-2")}>
                收支明细
              </Text>
            </View>
            <Icon
              type="ionicon"
              name="chevron-forward-outline"
              size={28}
              color="white"
            />
          </TouchableOpacity>
          {data?.role === 3 && (
            <TouchableOpacity
              onPress={() =>
                Linking.openURL(
                  `${process.env.EXPO_PUBLIC_WEB_URL}/withdrawal?mid=${data?.mid}&mobile_phone=${tokenAndMobilePhone?.mobile_phone}&token=${tokenAndMobilePhone?.token}`
                )
              }
              style={tailwind("flex-row justify-between items-center py-4")}
            >
              <View style={tailwind("flex-row items-center")}>
                <Icon
                  type="ionicon"
                  name="cash-outline"
                  size={32}
                  color="#fb923c"
                />
                <Text style={tailwind("text-base text-white font-medium ml-2")}>
                  提现
                </Text>
              </View>
              <Icon
                type="ionicon"
                name="chevron-forward-outline"
                size={28}
                color="white"
              />
            </TouchableOpacity>
          )}
        </View>
      </View>
    </View>
  );
}
