import { View, RefreshControl, FlatList } from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import Toast from "react-native-toast-message";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import SpacePost from "../../../components/SpacePost";
import Empty from "../../../components/Empty";

export default function SpacePosts({ navigation, route }) {
  const tailwind = useTailwind();

  const [data, setData] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const getData = async (type) => {
    if (!more && type !== "top") return;
    //防止重复加载
    if (data.length === 0 && type === "bottom") return;
    if (type === "bottom" && offset === 0) return;

    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        offset: type === "top" ? 0 : offset,
        limit: 4,
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/zone_moment/list_by_visitor_mid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            offset: type === "top" ? 0 : offset,
            limit: 4,
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      if (type === "top") {
        setData((prev) => _data.data.list);
      } else {
        setData((prev) => [...prev, ..._data.data.list]);
      }
      setOffset(_data.data.offset);
      setMore(_data.data.more);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getData("top");
  }, []);

  const renderItem = ({ item }) => <SpacePost data={item} />;

  const [refreshing, setRefreshing] = useState(false);
  //下拉刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    await getData("top");
    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="nodata" />}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}
