import { View, RefreshControl } from "react-native";
import React, { useState, useEffect } from "react";
import StreamerCard from "../../../components/StreamerCard";
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 { FlashList } from "@shopify/flash-list";

export default function FollowStream() {
  //获取关注的主播mid
  const [followMids, setFollowMids] = useState([]);
  const getFollowMids = async () => {
    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 (followMids.length === 0) {
      setData((prev) => []);
      return;
    }
    if (data.length === 0 && type === "bottom") 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/streamer/list_ext_by_mids?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mids: followMids,
            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(() => {
    getFollowMids();
  }, []);

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

  const tailwind = useTailwind();
  const renderItem = ({ item }) => <StreamerCard 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")}>
      <FlashList
        data={data}
        renderItem={renderItem}
        estimatedItemSize={287}
        initialNumToRender={4}
        refreshControl={
          <RefreshControl
            colors={["#FF669E"]}
            tintColor="white"
            refreshing={refreshing}
            onRefresh={() => handleRefresh()}
          />
        }
        onEndReached={() => getData("bottom")}
        ListEmptyComponent={<Empty type="friendship" />}
        keyExtractor={(item) => item.mid}
      />
    </View>
  );
}
