import { View, Text, RefreshControl, TouchableOpacity } from "react-native";
import React, { useState, useCallback, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import Empty from "../../../components/Empty";
import { FlashList } from "@shopify/flash-list";
import { useNavigation } from "@react-navigation/native";
import SpaceCard from "../../../components/SpaceCard";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import { useFocusEffect } from "@react-navigation/native";

export default function SpaceList() {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  const navigation = useNavigation();

  const [data, setData] = useState([]);
  const [more, setMore] = useState(true);
  const [offset, setOffset] = useState(0);
  const [currentUserId, setCurrentUserId] = useState(null);
  const getData = async (type, offset) => {
    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;
    const userId = await baseRequest();
    setCurrentUserId(userId?.b_mid);
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/zone/list_by_visitor_mid_v2?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            offset,
            limit: 6,
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }

      setOffset(_data.data.offset);
      setMore(_data.data.more);
      if (offset === 0) {
        setData(_data.data.list);
        return;
      }
      //在末尾添加元素以展示查看更多卡片
      setData((prev) => {
        return [...prev, ..._data.data.list];
      });
    } catch (error) {
      console.error(error);
    }
  };
  //每次focus都更新一次数据
  useFocusEffect(
    useCallback(() => {
      (async () => {
        const userId = await baseRequest();
        if (currentUserId !== userId?.b_mid) {
          setCurrentUserId(userId?.b_mid);
          getData("top", 0);
        }
      })();
    }, [])
  );
  const renderItem = ({ item }) => <SpaceCard data={item} />;

  //数据为空时的组件
  const EmptyComponent = useCallback(() => {
    return (
      <View style={tailwind("flex flex-col justify-center items-center")}>
        <Empty type="nospace" />
        <TouchableOpacity
          onPress={() => navigation.navigate("Search")}
          style={{
            width: 190,
            height: 46,
            ...tailwind(
              "flex items-center justify-center bg-[#FFFFFF1A] mt-3 rounded-full"
            ),
          }}
        >
          <Text style={tailwind("text-white text-base font-medium")}>
            搜索空间
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => navigation.navigate("Stream")}
          style={{
            width: 190,
            height: 46,
            ...tailwind(
              "flex items-center justify-center bg-[#FFFFFF1A] mt-2 rounded-full"
            ),
          }}
        >
          <Text style={tailwind("text-white text-base font-medium")}>
            查看推荐
          </Text>
        </TouchableOpacity>
      </View>
    );
  }, []);

  //下拉刷新
  const [refreshing, setRefreshing] = useState(false);
  const handleRefresh = async () => {
    setRefreshing(true);
    await getData("top", 0);
    setRefreshing(false);
  };

  return (
    <View
      style={{
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("flex-1 px-2")}>
        <FlashList
          data={data.length === 0 ? [] : [...data, { id: 999999, last: true }]}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          estimatedItemSize={166}
          initialNumToRender={12}
          numColumns={2}
          onEndReached={() => {
            getData("bottom", offset);
          }}
          drawDistance={10}
          refreshControl={
            <RefreshControl
              colors={["#FF669E"]}
              tintColor="white"
              refreshing={refreshing}
              onRefresh={() => handleRefresh()}
            />
          }
          ListEmptyComponent={EmptyComponent}
        />
      </View>
    </View>
  );
}
