import {
  View,
  RefreshControl,
  Image as NativeImage,
  Text,
  TouchableOpacity,
  FlatList,
} from "react-native";
import React, { useState, useEffect } from "react";
import Empty from "../../../components/Empty";
import { useTailwind } from "tailwind-rn";
import baseRequest from "../../../utils/baseRequest";
import Toast from "react-native-toast-message";
import { get } from "../../../utils/storeInfo";
import { generateSignature } from "../../../utils/crypto";
import Post from "../../../components/Post";
import { useNavigation } from "@react-navigation/native";

export default function FollowPosts({ blur }) {
  const navigation = useNavigation();

  //获取会员价格
  const [vipPrice, setVipPrice] = useState();
  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);
    }
  };

  //获取关注的主播mid
  const [followMids, setFollowMids] = useState([]);
  const [currentTime, setCurrentTime] = useState();
  const getFollowMids = async () => {
    setCurrentTime(Math.floor(new Date().getTime() / 1000));
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const account = await get("account");
      const signature = await generateSignature({
        mid: account.mid,
        offset: 0,
        limit: 100,
        ...base,
      });
      //查关注mid
      const response = await fetch(
        `${apiUrl}/api/account_relation/list_follow?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mid: account.mid,
            offset: 0,
            limit: 100,
            ...base,
          }),
        }
      );
      const temData = await response.json();
      if (temData.ret === -1) {
        Toast.show({
          type: "error",
          text1: temData.msg,
          topOffset: 60,
        });
        return;
      }
      const temFollowsMids = temData.data.list.map((item) => item.obj_mid);
      setFollowMids(temFollowsMids);
    } catch (error) {
      console.error(error);
    }
  };

  //获取主播动态
  const [data, setData] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const getData = async (type) => {
    if (!currentTime) return;
    if (followMids.length === 0) {
      setData((prev) => []);
      return;
    }

    //防止重复加载
    if (data.length === 0 && type === "bottom") return;
    if (type === "bottom" && offset === 0) return;

    if (!more) return;
    try {
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const base = await baseRequest();
      const signature = await generateSignature({
        mids: followMids,
        offset: offset,
        limit: 4,
        ...base,
      });
      //查关注主播展示资料
      const followsResponse = await fetch(
        `${apiUrl}/api/moment/list_by_mids?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mids: followMids,
            ct_upper_bound: currentTime,
            offset: offset,
            limit: 4,
            ...base,
          }),
        }
      );
      const followsData = await followsResponse.json();
      if (followsData.ret === -1) {
        Toast.show({
          type: "error",
          text1: followsData.msg,
          topOffset: 60,
        });
        return;
      }
      if (type === "top") {
        setData((prev) => followsData.data.list);
      } else {
        setData((prev) => [...prev, ...followsData.data.list]);
      }
      setOffset(followsData.data.offset);
      setMore(followsData.data.more);
    } catch (error) {
      console.error(error);
    }
  };

  //获取关注的主播mids
  useEffect(() => {
    getVipPrice();
    getFollowMids();
  }, []);

  //当关注的主播mids改变，获取新数据
  useEffect(() => {
    getData("top");
  }, [followMids, currentTime, blur]);

  const tailwind = useTailwind();
  const renderItem = ({ item }) => <Post isBlur={blur} data={item} />;
  const [refreshing, setRefreshing] = useState(false);
  //下拉刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    setOffset(0);
    setMore(1);
    await getFollowMids();
    setRefreshing(false);
  };

  return (
    <View style={tailwind("flex-1")}>
      <FlatList
        data={data}
        renderItem={renderItem}
        initialNumToRender={4}
        refreshControl={
          <RefreshControl
            colors={["#FF669E"]}
            tintColor="white"
            refreshing={refreshing}
            onRefresh={() => handleRefresh()}
          />
        }
        onEndReached={() => getData("bottom")}
        ListEmptyComponent={<Empty type="friendship" />}
        keyExtractor={(item) => item.id}
      />
      {blur && (
        <TouchableOpacity
          activeOpacity={1}
          onPress={() =>
            navigation.navigate("WebWithoutHeader", {
              uri: process.env.EXPO_PUBLIC_WEB_URL + "/vip",
            })
          }
          style={tailwind(
            "flex flex-row items-center justify-between h-12 bg-[#301024] px-4"
          )}
        >
          <View style={tailwind("flex flex-row items-center")}>
            <NativeImage
              source={require("../../../assets/icon/others/vipbig.png")}
            />
            <Text
              numberOfLines={1}
              ellipsizeMode="tail"
              style={tailwind("text-[#FF669E] text-base font-medium ml-1")}
            >
              即刻订阅全部精选内容
            </Text>
          </View>
          <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>
        </TouchableOpacity>
      )}
    </View>
  );
}
