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();
  useEffect(() => {
    const initData = async () => {
      const account = await get("account");
      const account_relation = await get("account_relation");
      setData({ ...account, ...account_relation });
    };
    initData();
  }, []);

  //每次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);
          //获取关注、粉丝数
          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);
          setData({ ...accountData.data.account, ...accountRelationData.data });
        } catch (error) {
          console.error(error);
        }
      };
      getData();
    }, [])
  );

  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")}>
                <Text
                  style={tailwind("text-2xl font-medium text-white mb-1.5")}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  {data?.name}
                </Text>
              </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>
            {data?.role === 3 && (
              <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>
          {/* 纵向列表设置区 */}
          {data?.role === 3 && (
            <View
              style={{
                ...tailwind("flex flex-col py-2 rounded-2xl mt-3.5 border-2"),
                borderColor: "#2c2b2f",
              }}
            >
              <TouchableOpacity
                onPress={() =>
                  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" }}>
                  创作者功能
                </Text>
                <NativeImage
                  source={require("../../assets/icon/32DP/smalllink.png")}
                />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => navigation.navigate("EditStreamerProfile")}
                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>
              <TouchableOpacity
                onPress={() => navigation.navigate("EditPlatformOrder")}
                style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
              >
                <NativeImage
                  source={require("../../assets/icon/32DP/editplatform.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>
              <TouchableOpacity
                onPress={() =>
                  navigation.navigate("WebWithHeader", {
                    title: "邀请有礼",
                    uri:
                      process.env.EXPO_PUBLIC_WEB_URL +
                      "/invite/" +
                      data?.user_id,
                  })
                }
                style={tailwind("flex flex-row h-12 items-center pr-2 pl-4")}
              >
                <NativeImage
                  source={require("../../assets/icon/32DP/sharemoney.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>
              <TouchableOpacity
                onPress={() =>
                  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" }}>
                  创作者功能
                </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")}
              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>
  );
}
