import { View, Text, Modal, TouchableOpacity, Alert } from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { Image } from "expo-image";
import { Icon } from "@rneui/themed";
import * as Clipboard from "expo-clipboard";
import { useNavigation } from "@react-navigation/native";
import { get } from "../../utils/storeInfo";
import baseRequest from "../../utils/baseRequest";
import Toast from "react-native-toast-message";
import { generateSignature } from "../../utils/crypto";

//todo:每次回来重新获取数据刷新余额、如果是本人则直接展示微信
//todo:等待接口上线，完善样式，测试

export default function GetWechatModal({ visible, setVisible, streamerMid }) {
  const tailwind = useTailwind();
  const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";
  const navigation = useNavigation();

  //保存用户数据
  const [userData, setUserData] = useState({});
  //保存主播数据
  const [streamerData, setStreamerData] = useState({});
  //保存用户数据
  const [wechat, setWechat] = useState("");
  //是否已经解锁微信
  const [isWechatUnlocked, setIsWechatUnlocked] = useState(false);
  //是否显示微信
  const [isWechatShow, setIsWechatShow] = useState(false);
  //是否展示余额不足内容
  const [isMoneyEnough, setIsMoneyEnough] = useState(true);

  useEffect(() => {
    const getInitData = async () => {
      const account = await get("account");
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const base = await baseRequest();
      const signature = await generateSignature({
        mid: streamerMid,
        ...base,
      });
      try {
        //获取主播数据
        const streamerResponse = await fetch(
          `${apiUrl}/api/streamer/list_ext_by_mid?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              mid: streamerMid,
              ...base,
            }),
          }
        );
        const temStreamerData = await streamerResponse.json();
        if (temStreamerData.ret === -1) {
          Toast.show({
            type: "error",
            text1: temStreamerData.msg,
            topOffset: 60,
          });
          return;
        }
        setStreamerData({
          ...temStreamerData.data.streamer_ext,
          wechat_coin_price:
            temStreamerData.data.streamer_ext.wechat_coin_price,
        });
        //是否已经解锁微信
        setIsWechatUnlocked(temStreamerData.data.is_unlock_wechat);
        //获取用户数据
        const signature2 = await generateSignature({
          ...base,
          mid: account.mid,
        });
        const userResponse = await fetch(
          `${apiUrl}/api/account/list_by_mid?signature=${signature2}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
              mid: account.mid,
            }),
          }
        );
        const temUserData = await userResponse.json();
        if (temUserData.ret === -1) {
          Toast.show({
            type: "error",
            text1: temUserData.msg,
            topOffset: 60,
          });
          return;
        }
        setUserData(temUserData.data.account);
      } catch (error) {
        console.error(error);
      }
    };
    if (!streamerMid) return;
    getInitData();
  }, [streamerMid]);

  //点击解锁微信按钮
  const unlockWechat = async () => {
    //余额不够就显示余额不足前往充值，够就直接购买
    if (userData?.gold_num >= streamerData?.wechat_coin_price) {
      //先支付，支付成功后添加解锁关系，再展示解锁界面
      //支付金币解锁微信
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const base = await baseRequest();
      const signature = await generateSignature({
        contact_product_id: "contact_wechat",
        uid: streamerMid,
        ...base,
      });
      try {
        const unlockResponse = await fetch(
          `${apiUrl}/api/vas/one_step_unlock?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              contact_product_id: "contact_wechat",
              uid: streamerMid,
              ...base,
            }),
          }
        );
        const unlockData = await unlockResponse.json();
        if (unlockData.ret === -1) {
          Toast.show({
            type: "error",
            text1: unlockData.msg,
            topOffset: 60,
          });
          return;
        }
        //展示解锁界面
        setIsWechatUnlocked(true);
      } catch (error) {
        console.error(error);
      }
    } else {
      setIsMoneyEnough(false);
    }
  };

  //获取微信并展示
  const showWechat = async () => {
    if (!isWechatShow) {
      //获取微信数据
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const base = await baseRequest();
      const signature = await generateSignature({
        uid: streamerMid,
        ...base,
      });
      try {
        const getWechatResponse = await fetch(
          `${apiUrl}/api/vas/query_wechat?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              uid: streamerMid,
              ...base,
            }),
          }
        );
        const getWechatData = await getWechatResponse.json();
        if (getWechatData.ret === -1) {
          Toast.show({
            type: "error",
            text1: getWechatData.msg,
            topOffset: 60,
          });
          return;
        }
        setWechat(getWechatData.data.wechat_contact);
      } catch (error) {
        console.error(error);
      }
      setIsWechatShow(true);
    } else {
      await Clipboard.setStringAsync(wechat);
      Alert.alert(null, "复制成功");
      setIsWechatShow(false);
    }
  };

  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-[#1E1C29] items-center")}
        >
          {isMoneyEnough ? (
            <>
              <View style={tailwind("items-center")}>
                <Image
                  style={tailwind("w-16 h-16 rounded-full absolute -top-12")}
                  source={streamerData?.avatar?.images[0]?.urls[0]}
                  placeholder={blurhash}
                  contentFit="cover"
                  transition={1000}
                  cachePolicy="disk"
                />
              </View>
              <Text style={tailwind("text-2xl text-white font-medium mt-4")}>
                {streamerData?.name}
              </Text>
              {/* 微信展示区 */}
              {isWechatUnlocked ? (
                <TouchableOpacity
                  style={{
                    ...tailwind(
                      "px-4 py-2 rounded-full mt-2 flex-row justify-center items-center"
                    ),
                    backgroundColor: isWechatShow ? "#FFFFFF1A" : "#FF669E",
                  }}
                  onPress={showWechat}
                >
                  {!isWechatShow && (
                    <Icon
                      type="ionicon"
                      name="lock-open"
                      color="#ffffff"
                      size={12}
                    />
                  )}
                  <Text style={tailwind("text-base text-white text-center")}>
                    {isWechatShow ? wechat : "已解锁·查看微信"}
                  </Text>
                  {isWechatShow && (
                    <Icon
                      type="ionicon"
                      name="copy"
                      color="#ffffff"
                      size={12}
                      containerStyle={tailwind("ml-2")}
                    />
                  )}
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  activeOpacity={1}
                  style={tailwind(
                    "flex-row px-4 py-2 bg-[#FFFFFF1A] rounded-xl mt-2 items-center justify-center"
                  )}
                >
                  <Icon
                    type="ionicon"
                    name="lock-closed"
                    color="#ffffff"
                    size={12}
                  />
                  <Text style={tailwind("text-base text-white")}>
                    解锁后展示
                  </Text>
                </TouchableOpacity>
              )}
              <Text style={tailwind("text-xs text-[#F53030] my-2")}>
                添加时请备注自己“铁粉空间”昵称
              </Text>
              <Text style={tailwind("text-xs text-[#F53030] mb-2")}>
                若解锁后72小时未通过好友，请联系客服
              </Text>
              {!isWechatUnlocked && (
                <TouchableOpacity
                  onPress={unlockWechat}
                  style={tailwind(
                    "px-4 py-2 bg-[#FF669E] rounded-full items-center justify-center"
                  )}
                >
                  <Text style={tailwind("text-white text-base")}>
                    解锁微信（{streamerData?.wechat_coin_price}金币）
                  </Text>
                </TouchableOpacity>
              )}
            </>
          ) : (
            <>
              <Text style={tailwind("text-2xl text-white font-medium mb-4")}>
                余额不足
              </Text>
              <TouchableOpacity
                onPress={() => {
                  navigation.navigate("Wallet");
                  setVisible(false);
                }}
                style={tailwind(
                  "px-4 py-2 bg-[#FF669E] rounded-full items-center justify-center"
                )}
              >
                <Text style={tailwind("text-white text-base")}>前往充值</Text>
              </TouchableOpacity>
            </>
          )}
        </TouchableOpacity>
      </TouchableOpacity>
    </Modal>
  );
}
