import {
  View,
  Text,
  FlatList,
  RefreshControl,
  Image as NativeImage,
} from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import Toast from "react-native-toast-message";
import Empty from "../../../../components/Empty";
import { ListItem, Icon } from "@rneui/themed";
import { Image } from "expo-image";
import baseRequest from "../../../../utils/baseRequest";
import { generateSignature } from "../../../../utils/crypto";
import formatTimestamp from "../../../../utils/formatTimestamp";

export default function IronfanSpaceMember({ zid }) {
  const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";

  const tailwind = useTailwind();
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const [data, setData] = useState([]);
  const getData = async () => {
    if (zid === undefined || !more) return;
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const body = {
        zid: zid,
        member_type: 2,
        offset: offset,
        limit: 20,
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone/member_list?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(_data.data.list);
      setOffset(_data.data.offset);
      setMore(_data.data.more);
    } catch (error) {
      console.error(error);
    }
  };

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

  //下拉刷新
  const [refreshing, setRefreshing] = useState(false);

  //下拉刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    await getData();
    setRefreshing(false);
  };

  //单个成员组件
  const renderItem = ({ item }) => {
    return (
      <ListItem bottomDivider containerStyle={tailwind("p-0 bg-transparent")}>
        <View style={tailwind("flex-1")}>
          <View style={tailwind("flex-row py-3")}>
            <Image
              style={tailwind("w-12 h-12 rounded-full")}
              source={item?.account?.avatar?.images[0]?.urls[0]}
              placeholder={blurhash}
              contentFit="cover"
              transition={1000}
              cachePolicy="disk"
            />
            <View style={tailwind("ml-2 justify-around flex-1")}>
              <Text
                style={tailwind("text-base text-white font-medium")}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                {item?.account?.name}
              </Text>
              <View style={tailwind("flex-row flex-wrap")}>
                <View
                  style={tailwind(
                    "flex-row items-center py-0.5 px-2 mr-2 bg-[#FFFFFF1A] rounded-full"
                  )}
                >
                  <NativeImage
                    source={require("../../../../assets/icon/12DP/ID.png")}
                  />
                  <Text
                    style={tailwind("text-white text-xs font-medium ml-0.5")}
                  >
                    {item?.account?.user_id}
                  </Text>
                </View>
                <View
                  style={tailwind(
                    "flex-row items-center py-0.5 px-2 mr-2 bg-[#FFFFFF1A] rounded-full"
                  )}
                >
                  <Icon
                    type="ionicon"
                    name="calendar-outline"
                    size={12}
                    color="white"
                  />
                  <Text
                    style={tailwind("text-white text-xs font-medium ml-0.5")}
                  >
                    {formatTimestamp(item?.join_ct)}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      </ListItem>
    );
  };

  return (
    <View style={tailwind("px-4 flex-1")}>
      <FlatList
        data={data}
        renderItem={renderItem}
        initialNumToRender={12}
        refreshControl={
          <RefreshControl
            colors={["#FF669E"]}
            tintColor="white"
            refreshing={refreshing}
            onRefresh={() => handleRefresh()}
          />
        }
        ononEndReached={() => getData()}
        ListEmptyComponent={<Empty type="nodata" />}
        ListHeaderComponent={() => (
          <View
            style={tailwind(
              "flex flex-row p-1 justify-center items-center bg-[#FFFFFF1A] rounded-lg"
            )}
          >
            <Text style={tailwind("text-white text-sm font-medium")}>
              铁粉总人数：{data?.length}
            </Text>
          </View>
        )}
      />
    </View>
  );
}
