import {
  View,
  TouchableOpacity,
  Image as NativeImage,
  Dimensions,
} from "react-native";
import React, { useState, useEffect, useCallback } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Tab, TabView } from "@rneui/themed";
import FeedPosts from "./FeedPosts";
import FollowPosts from "./FollowPosts";
import { get, save } from "../../utils/storeInfo";
import { useFocusEffect } from "@react-navigation/native";
import baseRequest from "../../utils/baseRequest";
import { generateSignature } from "../../utils/crypto";

export default function Posts({ navigation }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [index, setIndex] = useState(0);

  //修复ios使用了tab组件闪退问题
  const [indicatorX, setIndicatorX] = useState(0);
  const windowWidth = Dimensions.get("window").width;
  const tabWidth = windowWidth / 5;

  //根据用户是否是主播来决定是否展示发帖按钮
  const [isStreamer, setIsStreamer] = useState(false);
  useEffect(() => {
    const checkRole = async () => {
      const account = await get("account");
      const role = account.role;
      if (role === 3) {
        setIsStreamer(true);
      }
    };
    checkRole();
  }, []);

  //每次focus都更新一次数据，查看会员状态是否改变
  const [blur, setBlur] = useState(true);
  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;
          }
          const role = accountData.data.account.role;
          const isVip = accountData.data.account.is_a_member;
          if (role !== 0 || isVip === 1) {
            setBlur(false);
          }
          await save("account", accountData.data.account);
        } catch (error) {
          console.error(error);
        }
      };
      getData();
    }, [])
  );

  return (
    <View
      style={{
        paddingTop: insets.top,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex flex-1"),
      }}
    >
      <View style={tailwind("flex pb-1 flex-row justify-between items-center")}>
        <View style={tailwind("flex w-2/5")}>
          <Tab
            value={index}
            onChange={(e) => {
              setIndex(e);
              setIndicatorX(e * tabWidth);
            }}
            dense
            indicatorStyle={{
              ...tailwind("h-1 w-10 ml-4 rounded-full"),
              backgroundColor: "#FF7DCB",
              transform: [{ translateX: indicatorX }],
            }}
          >
            <Tab.Item
              titleStyle={
                index === 0
                  ? tailwind("text-white text-2xl font-medium")
                  : { ...tailwind("text-2xl font-medium"), color: "#FFFFFF80" }
              }
            >
              推荐
            </Tab.Item>
            <Tab.Item
              titleStyle={
                index === 1
                  ? tailwind("text-white text-2xl font-medium")
                  : { ...tailwind("text-2xl font-medium"), color: "#FFFFFF80" }
              }
            >
              关注
            </Tab.Item>
          </Tab>
        </View>
        <TouchableOpacity
          style={tailwind(
            "flex items-center justify-center w-9 h-9 mr-4 bg-[#FFFFFF1A] rounded-full"
          )}
          onPress={() => navigation.navigate("Search")}
        >
          <NativeImage source={require("../../assets/icon/32DP/search.png")} />
        </TouchableOpacity>
      </View>
      <View style={tailwind("flex flex-1 w-full")}>
        <TabView
          value={index}
          onChange={(e) => {
            setIndex(e);
            setIndicatorX(e * tabWidth);
          }}
          animationType="spring"
        >
          <TabView.Item style={tailwind("w-full flex-1")}>
            <FeedPosts blur={blur} />
          </TabView.Item>
          <TabView.Item style={tailwind("w-full flex-1")}>
            <FollowPosts blur={blur} />
          </TabView.Item>
        </TabView>
      </View>
      {isStreamer && (
        <TouchableOpacity
          onPress={() => navigation.navigate("CreatePost")}
          style={tailwind("absolute right-3 bottom-5 rounded-full")}
        >
          <NativeImage
            source={require("../../assets/icon/others/createpost.png")}
          />
        </TouchableOpacity>
      )}
    </View>
  );
}
