import { Box, Flex, ScrollArea, Text } from "@radix-ui/themes";
import { useInfiniteQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useInView } from "react-intersection-observer";
import { SelectedPostsResponse } from "../../@types/PostTypes";
import { axiosLocalhost } from "../../api/axios/axios";
import PostCard from "./PostCard/PostCard";

const LIMIT = 7;

export default function RandomPostsPage() {
	const { t } = useTranslation();

	const [ref, inView] = useInView();

	const { data, isFetching, fetchNextPage, hasNextPage } = useInfiniteQuery({
		queryKey: [`random_post_inf`],
		queryFn: async ({ pageParam }): Promise<SelectedPostsResponse> => {
			const response = await axiosLocalhost.get(
				`/posts/random?limit=${LIMIT}&offset=${pageParam}`
			);

			return response.data as SelectedPostsResponse;
		},
		initialPageParam: 0,
		getPreviousPageParam: (lastPage) =>
			lastPage.prev_page_index < 0 ? undefined : lastPage.prev_page_index,
		getNextPageParam: (lastPage) =>
			lastPage.next_page_index < 0 ? undefined : lastPage.next_page_index,
	});

	useEffect(() => {
		if (inView) {
			if (hasNextPage) fetchNextPage();
		}
	}, [inView]);

	return (
		<>
			<ScrollArea>
				<Flex
					direction={"column"}
					className="w-full overflow-hidden sm:mx-auto max-w-pc-width "
				>
					<Flex direction={"column"} gap={"4"}>
						{data?.pages.map((post, i) => {
							return (
								<Flex
									direction={"column"}
									gap={"4"}
									key={`${i}`}
								>
									{post.selected_posts.map((post, j) => {
										return <PostCard key={j} {...post} />;
									})}
								</Flex>
							);
						})}

						<Box ref={ref} className="w-full mb-4 text-center">
							{isFetching ? (
								<Text>Loading more...</Text>
							) : hasNextPage ? (
								<Text
									className="cursor-pointer"
									onClick={() => fetchNextPage()}
								>
									Load more posts
								</Text>
							) : (
								<Text>No more posts to load</Text>
							)}
						</Box>
					</Flex>
				</Flex>
			</ScrollArea>
		</>
	);
}
