import React, { useEffect } from "reactn";
import { Text, View, FlatList } from "react-native";
import { useDataFromRef } from "react-native-minuit/src/hooks";
import moment from "moment";
import { Motion } from "@legendapp/motion";

import Page from "../layouts/Page";

import { Fonts, Style } from "../styles";
import { notificationsRef } from "../config/firebase";

import { LoaderIndicator } from "../providers/LoadingProvider";

export default (props) => {
  const baseNotificationRef = notificationsRef;

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

  const markAsRead = async () => {
    try {
    } catch (error) {
      console.error(error);
    }
  };

  const {
    data: notificationList,
    loading,
    loadMore,
  } = useDataFromRef({
    ref: baseNotificationRef.orderBy("timestamp", "desc"),
    usePagination: true,
    batchSize: 40,
    documentID: "notificationID",
  });

  return (
    <Page headerType="NAVIGATE" title="Notifications">
      <FlatList
        removeClippedSubviews={true}
        estimatedItemSize={100}
        showsVerticalScrollIndicator={false}
        data={notificationList}
        renderItem={({ item, index }) => {
          const { title = "", timestamp } = item;

          const randomDuration = Math.floor(Math.random() * 1000) + 500;

          return (
            <Motion.Pressable
              key={index}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{
                opacity: {
                  type: "tween",
                  duration: randomDuration,
                },
              }}
              style={Style.containerSpaceBetween}
              onPress={() => {}}
            >
              <View style={Style.containerRow}>
                <Text
                  numberOfLines={2}
                  style={Fonts({ style: { width: "100%" } })}
                >
                  {title}
                </Text>
              </View>

              <Text style={Fonts({ style: { opacity: 0.5 } })}>
                {moment(timestamp.toDate()).format("[Le] DD/MM [à] HH:mm")}
              </Text>
            </Motion.Pressable>
          );
        }}
        keyExtractor={(item) =>
          `Notifications_${item.notificationID}_${item.projectID}`
        }
        ItemSeparatorComponent={() => (
          <View style={{ ...Style.separatorHorizontal }} />
        )}
        ListFooterComponent={loading ? <LoaderIndicator /> : null}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
      />
    </Page>
  );
};
