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

//todo:等接口上线补全字段
export default function PostPurchasers({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //查询数据
  const [data, setData] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const apiUrl = process.env.EXPO_PUBLIC_API_URL;
  const getData = async () => {
    if (!more) return;
    try {
      const base = await baseRequest();
      const body = {
        moment_id: route.params.id,
        offset: offset,
        limit: 12,
        ...base,
      };
      const signature = await generateSignature(body);
      const response = await fetch(
        `${apiUrl}/api/vas/moment_order_list?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const temData = await response.json();
      if (temData.ret === -1) {
        Toast.show({
          type: "error",
          text1: temData.msg,
          topOffset: 60,
        });
        return;
      }
      setData((prev) => [...prev, ...temData.data.list]);
      setOffset(temData.data.offset);
      setMore(temData.data.more);
    } catch (error) {
      console.error(error);
    }
  };

  //格式化时间
  const formatDate = useCallback((timestamp) => {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始,所以需要加1
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    return `${year}/${month}/${day} ${hours}:${minutes}`;
  }, []);

  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]}
              contentFit="cover"
              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 mt-1.5")}>
                <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")}
                  >
                    {formatDate(item?.buy_time)}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      </ListItem>
    );
  };

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("px-4 flex-1")}>
        <FlatList
          data={data}
          renderItem={renderItem}
          initialNumToRender={12}
          onEndReached={() => getData()}
          ListEmptyComponent={<Empty type="nodata" />}
        />
      </View>
    </View>
  );
}
