import { Box, Typography, Stack, CircularProgress } from "@mui/joy";
import { useAppSelector, useAppDispatch } from "../../store/hooks";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { fetchNewsItems } from "../../store/newsItemSlice";
import NewsItemCard from "./cards/NewsItemCard";
import { NewsItem } from "../../model/NewsItem";

function LatestNews() {
    const limit: number = 20;

    const newsItems = useAppSelector((state) => state.newsItem.all);
    const status = useAppSelector((state) => state.newsItem.status);
    const dispatch = useAppDispatch();

    const page = useRef(1);
    const observer = useRef<any>();

    const [newsItemsAll, setNewsItemsAll] = useState(Array<NewsItem>);

    const lastNewsItemRef = useCallback((node: any) => {
        if (status === "loading") return;
        if (observer.current) observer.current.disconnect();
        observer.current = new IntersectionObserver(entries => {
            if (entries[0].isIntersecting) {
                page.current++;
                dispatch(fetchNewsItems({ page: page.current, limit }));
            }
        });
        if (node) observer.current.observe(node);
    }, [status, dispatch]);

    useEffect(() => {
        dispatch(fetchNewsItems({ page: page.current, limit }));
    }, [dispatch]);

    useEffect(() => {
        setNewsItemsAll(n => [...n, ...newsItems.data]);
    }, [newsItems.data]);

    return (
        <div>
            <Typography level="h2" component="h1">
                Latest News
            </Typography>

            <Stack
                sx={{ marginTop: 2, marginBottom: 2 }}
                direction="column"
                justifyContent="flex-start"
                alignItems="stretch"
                spacing={2}
            >
                {newsItemsAll.map((newsItem, index) => {
                    if (newsItemsAll.length === index + 1) {
                        return <div ref={lastNewsItemRef} key={newsItem.id}>
                            <NewsItemCard key={'card-' + newsItem.id} newsItem={newsItem} />
                        </div>;
                    }
                    return <div key={newsItem.id}>
                        <NewsItemCard key={'card-' + newsItem.id} newsItem={newsItem} />
                    </div>;
                })}

                {status === "loading" &&
                    <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                        <CircularProgress thickness={1} />
                    </Box>
                }
            </Stack>
        </div>
    );
}

export default LatestNews;