import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Image as NativeImage,
} from "react-native";
import React, { useState, useEffect, useCallback } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Icon } from "@rneui/themed";
import { Image } from "expo-image";
import Toast from "react-native-toast-message";
import { get, save } from "../../utils/storeInfo";
import baseRequest from "../../utils/baseRequest";
import { useFocusEffect } from "@react-navigation/native";
import { generateSignature } from "../../utils/crypto";

const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";

export default function My({ navigation }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //获取当前页面数据
  const [data, setData] = useState();
  const [vipPrice, setVipPrice] = useState();
  useEffect(() => {
    const initData = async () => {
      const account = await get("account");
      const account_relation = await get("account_relation");
      setData({ ...account, ...account_relation });
    };
    const getVipPrice = async () => {
      try {
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
        });
        const _response = await fetch(
          `${apiUrl}/api/vas/get_membership_product_list?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
            }),
          }
        );
        const _data = await _response.json();
        if (_data.ret === -1) {
          Toast.show({
            type: "error",
            text1: _data.msg,
            topOffset: 60,
          });
          return;
        }
        setVipPrice(_data.data.product.real_price / 100);
      } catch (error) {
        console.error(error);
      }
    };
    initData();
    getVipPrice();
  }, []);

  //每次focus都更新一次数据
  const [isInJoinProgress, setIsInJoinProgress] = useState(false);
  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);
          const oldAccount = await get(
            `account_list_${accountData.data.account.user_id}`
          );
          await save(`account_list_${accountData.data.account.user_id}`, {
            ...oldAccount,
            account: accountData.data.account,
            login_time: new Date().getTime(),
          });
          //获取关注、粉丝数
          const signature2 = await generateSignature({
            ...base,
            mid: account.mid,
          });
          const accountRelationResponse = await fetch(
            `${apiUrl}/api/account_relation/count?signature=${signature2}`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                ...base,
                mid: account.mid,
              }),
            }
          );
          const accountRelationData = await accountRelationResponse.json();
          if (accountRelationData.ret === -1) {
            Toast.show({
              type: "error",
              text1: accountRelationData.msg,
              topOffset: 60,
            });
            return;
          }
          await save("account_relation", accountRelationData.data);
          if (accountData.data.account.role === 3) {
            //获取主播信息
            const signature3 = await generateSignature({
              ...base,
              mid: account.mid,
            });
            const streamerResponse = await fetch(
              `${apiUrl}/api/streamer/list_ext_by_mid?signature=${signature3}`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  ...base,
                  mid: account.mid,
                }),
              }
            );
            const streamerData = await streamerResponse.json();
            if (streamerData.ret === -1) {
              Toast.show({
                type: "error",
                text1: streamerData.msg,
                topOffset: 60,
              });
              return;
            }
            setData({
              ...accountData.data.account,
              ...accountRelationData.data,
              ...streamerData.data,
            });
            return;
          }
          setData({ ...accountData.data.account, ...accountRelationData.data });
        } catch (error) {
          console.error(error);
        }
      };
      //查看用户是否正在申请成为主播
      const getBasicStatus = async () => {
        //获取环境变量
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const base = await baseRequest();
        const body = {
          ...base,
        };
        const signature = await generateSignature(body);
        try {
          //获取账号基本信息
          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;
          }
          if (
            _data.data.basic_status === 0 ||
            _data.data.basic_status === 1 ||
            _data.data.basic_status === 3
          )
            setIsInJoinProgress(true);
        } catch (error) {
          console.error(error);
        }
      };
      getData();
      getBasicStatus();
    }, [])
  );

  //通过toast向准主播提示需要先补充资料
  const remainCompleteInformation = (func) => {
    if (data?.role === 3) {
      func();
      return;
    }
    Toast.show({
      type: "error",
      text1: "请先完善资料并等待审核通过",
      topOffset: 60,
    });
  };

  return (
    <ScrollView>
      <View
        style={{
          paddingBottom: insets.bottom,
          paddingLeft: insets.left,
          paddingRight: insets.right,
        }}
      >
        <NativeImage
          style={tailwind("absolute top-0 left-0")}
          source={require("../../assets/icon/others/profilebackground.png")}
        />
        <View style={{ paddingTop: insets.top, ...tailwind("px-4") }}>
          <View style={tailwind("flex-row h-12 justify-end items-center")}>
            <TouchableOpacity
              onPress={() => navigation.navigate("EditUserProfile")}
              style={tailwind("bg-[#FFFFFF1A] rounded-full mr-2")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/edit.png")}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => navigation.navigate("Setting")}
              style={tailwind("bg-[#FFFFFF1A] rounded-full")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/setting.png")}
              />
            </TouchableOpacity>
          </View>
          {/* 头像、id、昵称 */}
          <TouchableOpacity
            activeOpacity={1}
            onPress={() => {
              if (data?.role === 3) {
                navigation.navigate("StreamerProfile", {
                  mid: data?.mid,
                });
              } else {
                navigation.navigate("UserProfile");
              }
            }}
            style={tailwind("flex flex-row items-center h-24")}
          >
            <Image
              style={tailwind("w-[4.6rem] h-[4.6rem] rounded-full")}
              source={data?.avatar?.images[0]?.urls[0]}
              placeholder={blurhash}
              contentFit="cover"
              transition={1000}
              cachePolicy="disk"
            />
            <View style={tailwind("flex flex-col ml-2 h-20 justify-center")}>
              <View style={tailwind("flex flex-row items-center mb-1.5")}>
                <Text
                  style={{
                    color: data?.is_a_member === 1 ? "#FFADBE" : "white",
                    ...tailwind("text-2xl font-medium"),
                  }}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  {data?.name}
                </Text>
                {data?.is_a_member === 1 && (
                  <NativeImage
                    source={require("../../assets/icon/others/vipbig.png")}
                  />
                )}
              </View>
              <View style={tailwind("flex-row")}>
                <View
                  style={{
                    backgroundColor: "#FFFFFF1A",
                    ...tailwind("rounded-full px-2"),
                  }}
                >
                  <Text style={tailwind("text-xs text-white")}>
                    <Text style={tailwind("font-medium")}>ID </Text>
                    {data?.user_id}
                  </Text>
                </View>
              </View>
            </View>
            <View style={tailwind("ml-auto")}>
              <Icon
                name="chevron-forward-outline"
                type="ionicon"
                color="#ffffff"
              />
            </View>
          </TouchableOpacity>
          {/* 关注、粉丝、金币、钻石 */}
          <View style={tailwind("flex flex-row justify-around mt-2 w-full")}>
            <TouchableOpacity
              onPress={() => navigation.navigate("Relationship", { tab: 0 })}
              style={tailwind("flex flex-col items-center w-1/4")}
            >
              <Text style={tailwind("text-2xl font-medium text-white")}>
                {data?.follow_count}
              </Text>
              <Text
                style={{
                  color: "#FFFFFF80",
                  ...tailwind("text-sm font-medium"),
                }}
              >
                关注
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => navigation.navigate("Relationship", { tab: 1 })}
              style={tailwind("flex flex-col items-center w-1/4")}
            >
              <Text style={tailwind("text-2xl font-medium text-white")}>
                {data?.is_followed_count}
              </Text>
              <Text
                style={{
                  color: "#FFFFFF80",
                  ...tailwind("text-sm font-medium"),
                }}
              >
                粉丝
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => navigation.navigate("Wallet")}
              style={tailwind("flex flex-col items-center w-1/4")}
            >
              <Text style={tailwind("text-2xl font-medium text-white")}>
                {data?.gold_num}
              </Text>
              <Text
                style={{
                  color: "#FFFFFF80",
                  ...tailwind("text-sm font-medium"),
                }}
              >
                金币
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => navigation.navigate("Wallet")}
              style={tailwind("flex flex-col items-center w-1/4")}
            >
              <Text style={tailwind("text-2xl font-medium text-white")}>
                {data?.diamond_num}
              </Text>
              <Text
                style={{
                  color: "#FFFFFF80",
                  ...tailwind("text-sm font-medium"),
                }}
              >
                钻石
              </Text>
            </TouchableOpacity>
          </View>
          {/* 会员 */}
          <TouchableOpacity
            activeOpacity={1}
            onPress={() =>
              navigation.navigate("WebWithoutHeader", {
                uri: process.env.EXPO_PUBLIC_WEB_URL + "/vip",
              })
            }
            style={tailwind(
              "flex flex-col p-2.5 rounded-2xl mt-3.5 bg-[#301024]"
            )}
          >
            <View
              style={tailwind("flex flex-row justify-between items-center")}
            >
              <View style={tailwind("flex flex-col")}>
                <View style={tailwind("flex flex-row items-center")}>
                  <NativeImage
                    source={require("../../assets/icon/others/vipsmall.png")}
                  />
                  <Text
                    style={tailwind("text-base text-[#FF669E] font-medium")}
                  >
                    {data?.is_a_member !== 1
                      ? "开通会员保存图片"
                      : "尊贵的永久会员"}
                  </Text>
                </View>
                <Text style={tailwind("text-sm text-[#FFFFFF40] font-medium")}>
                  {data?.is_a_member !== 1
                    ? "限时优惠活动"
                    : "已解锁全部会员权益"}
                </Text>
              </View>
              {data?.is_a_member !== 1 && (
                <View
                  style={tailwind(
                    "flex justify-center items-center h-9 bg-[#FF669E] rounded-full px-4"
                  )}
                >
                  <Text style={tailwind("text-white text-sm font-medium")}>
                    ¥{vipPrice}/永久
                  </Text>
                </View>
              )}
            </View>
          </TouchableOpacity>
          {/* 纵向列表设置区 */}
          {(data?.role === 3 || isInJoinProgress) && (
            <View
              style={{
                ...tailwind("flex flex-col py-2 rounded-2xl mt-3.5 border-2"),
                borderColor: "#2c2b2f",
              }}
            >
              {isInJoinProgress && (
                <TouchableOpacity
                  onPress={() =>
                    navigation.navigate("StreamerVerification", {
                      screen: "CompleteStreamerInformation",
                    })
                  }
                  style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
                >
                  <NativeImage
                    source={require("../../assets/icon/32DP/editprofile.png")}
                  />
                  <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                    完善资料
                  </Text>
                  <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                    完善后解锁全部功能
                  </Text>
                  <NativeImage
                    source={require("../../assets/icon/32DP/smalllink.png")}
                  />
                </TouchableOpacity>
              )}
              {data?.streamer_ext?.zones?.length === 0 ? (
                <TouchableOpacity
                  onPress={() =>
                    remainCompleteInformation(() =>
                      navigation.navigate("CreateSpace")
                    )
                  }
                  style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
                >
                  <NativeImage
                    source={require("../../assets/icon/others/myposts.png")}
                  />
                  <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                    开通空间
                  </Text>
                  <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                    {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                  </Text>
                  <NativeImage
                    source={require("../../assets/icon/32DP/smalllink.png")}
                  />
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  onPress={() =>
                    remainCompleteInformation(() =>
                      navigation.navigate("StreamerSpace", { mid: data?.mid })
                    )
                  }
                  style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
                >
                  <NativeImage
                    source={require("../../assets/icon/others/space.png")}
                  />
                  <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                    我的空间
                  </Text>
                  <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                    {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                  </Text>
                  <NativeImage
                    source={require("../../assets/icon/32DP/smalllink.png")}
                  />
                </TouchableOpacity>
              )}
              <TouchableOpacity
                onPress={() =>
                  remainCompleteInformation(() =>
                    navigation.navigate("StreamerPosts", { mid: data?.mid })
                  )
                }
                style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
              >
                <NativeImage
                  source={require("../../assets/icon/others/myposts.png")}
                />
                <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                  广场动态
                </Text>
                <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                  {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                </Text>
                <NativeImage
                  source={require("../../assets/icon/32DP/smalllink.png")}
                />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() =>
                  remainCompleteInformation(() =>
                    navigation.navigate("WechatWaitingToAdd", { tab: 0 })
                  )
                }
                style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
              >
                <NativeImage
                  source={require("../../assets/icon/32DP/wechat.png")}
                />
                <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                  待添加微信
                </Text>
                <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                  {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                </Text>
                <NativeImage
                  source={require("../../assets/icon/32DP/smalllink.png")}
                />
              </TouchableOpacity>
              {data?.role === 3 && (
                <TouchableOpacity
                  onPress={() =>
                    remainCompleteInformation(() =>
                      navigation.navigate("EditStreamerInfo")
                    )
                  }
                  style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
                >
                  <NativeImage
                    source={require("../../assets/icon/32DP/editprofile.png")}
                  />
                  <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                    编辑资料
                  </Text>
                  <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                    {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                  </Text>
                  <NativeImage
                    source={require("../../assets/icon/32DP/smalllink.png")}
                  />
                </TouchableOpacity>
              )}
              <TouchableOpacity
                onPress={() =>
                  remainCompleteInformation(() =>
                    navigation.navigate("WebWithHeader", {
                      title: "我的专属链接",
                      uri:
                        process.env.EXPO_PUBLIC_WEB_URL +
                        "/generatelink/" +
                        data?.user_id,
                    })
                  )
                }
                style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
              >
                <NativeImage
                  source={require("../../assets/icon/32DP/share.png")}
                />
                <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                  生成分享页
                </Text>
                <Text style={{ ...tailwind("text-xs"), color: "#FFFFFF80" }}>
                  {data?.role === 3 ? "创作者功能" : "完善资料后解锁"}
                </Text>
                <NativeImage
                  source={require("../../assets/icon/32DP/smalllink.png")}
                />
              </TouchableOpacity>
            </View>
          )}
          <View
            style={{
              ...tailwind("flex flex-col py-2 rounded-2xl mt-3.5 border-2"),
              borderColor: "#2c2b2f",
            }}
          >
            <TouchableOpacity
              onPress={() => navigation.navigate("Wallet")}
              style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/wallet.png")}
              />
              <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                我的钱包
              </Text>
              <NativeImage
                source={require("../../assets/icon/32DP/smalllink.png")}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => navigation.navigate("UnlockedWechat")}
              style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/wechat.png")}
              />
              <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                已解锁微信
              </Text>
              <NativeImage
                source={require("../../assets/icon/32DP/smalllink.png")}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() =>
                navigation.navigate("StreamerVerification", {
                  screen: "JoinStreamer",
                })
              }
              style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/join.png")}
              />
              <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                申请入驻
              </Text>
              <NativeImage
                source={require("../../assets/icon/32DP/smalllink.png")}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() =>
                navigation.navigate("MessageDetail", {
                  mid: 1,
                })
              }
              style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
            >
              <NativeImage
                source={require("../../assets/icon/32DP/contact.png")}
              />
              <Text style={tailwind("text-base text-white ml-2 flex-1")}>
                联系客服
              </Text>
              <NativeImage
                source={require("../../assets/icon/32DP/smalllink.png")}
              />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </ScrollView>
  );
}
