import { View, ActivityIndicator } from "react-native";
import React, { useState } from "react";
import { useTailwind } from "tailwind-rn";
import Toast from "react-native-toast-message";
import Empty from "../../../components/Empty";
import { BottomSheetFlatList } from "@gorhom/bottom-sheet";
import SpacePost from "../../../components/SpacePost";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function AllSpacePosts({ zid }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  const [data, setData] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const [isFetching, setIsFetching] = useState(false);
  const getData = async () => {
    if (zid === undefined) return;
    if (!more) return;
    if (isFetching) return;
    setIsFetching(true);
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const body = {
        zid: zid,
        ct_upper_bound: Math.floor(new Date().getTime() / 1000),
        offset: offset,
        limit: 4,
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone_moment/list_by_zid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      setData((prev) => [...prev, ..._data.data.list]);
      setOffset(_data.data.offset);
      setMore(_data.data.more);
    } catch (error) {
      console.error(error);
    } finally {
      setIsFetching(false);
    }
  };

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

  return (
    <BottomSheetFlatList
      data={data}
      keyExtractor={(i) => i.id}
      renderItem={renderItem}
      contentContainerStyle={{
        paddingBottom: 150 + insets.bottom,
        ...tailwind("bg-[#07050A]"),
      }}
      onEndReached={() => getData()}
      ListFooterComponent={() => (
        <View>
          {data.length !== 0 && more === 1 && (
            <ActivityIndicator style={tailwind("my-4")} size="large" />
          )}
        </View>
      )}
      ListEmptyComponent={<Empty type="nodata" />}
    />
  );
}
