"use client";

import Image from "next/image";
import Link from "next/link";
import { useInfiniteQuery } from "@tanstack/react-query";
import { fetchPosts } from "@/api/fetchPosts";
import { Post } from "@/types/types";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import Cookies from "js-cookie";
import { useCallback, useEffect } from "react";
import PageLoader from "@/components/ui/PageLoader";

function getThumb(post: Post) {
  const file = post.files?.[0];
  if (!file?.path) return null;
  return `${IMAGE_BASE_URL}${file.path.replace("/root/modstagram-back/storage", "")}`;
}

export default function ExploreGrid() {
  const token = Cookies.get("token") || "";

  const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } =
    useInfiniteQuery({
      queryKey: ["explore-videos"],
      queryFn: ({ pageParam = 1 }) =>
        fetchPosts(pageParam as number, 12, { type: "video" }, token),
      getNextPageParam: (lastPage, allPages) =>
        lastPage.posts.length > 0 ? allPages.length + 1 : undefined,
      initialPageParam: 1,
    });

  const handleScroll = useCallback(() => {
    if (
      window.innerHeight + window.scrollY >=
      document.body.offsetHeight - 800
    ) {
      if (hasNextPage && !isFetchingNextPage) fetchNextPage();
    }
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [handleScroll]);

  const videos =
    data?.pages.flatMap((p) => p.posts).filter((p) => p.status === "accept") ?? [];

  if (isLoading) return <PageLoader className="min-h-[40vh]" />;

  if (!videos.length) {
    return (
      <p className="py-16 text-center text-sm text-neutral-500">
        ویدئویی برای نمایش وجود ندارد.
      </p>
    );
  }

  return (
    <div className="grid grid-cols-3 gap-1.5 p-2 sm:gap-2 sm:p-3">
      {videos.map((post) => {
        const src = getThumb(post);
        if (!src) return null;
        return (
          <Link
            key={post._id}
            href={`/explore/${post._id}`}
            className="gentle-transition relative aspect-[3/4] overflow-hidden rounded-2xl active:scale-[0.98]"
          >
            <Image src={src} alt="" fill className="object-cover" sizes="33vw" />
            <span className="absolute bottom-2 left-2 rounded-full bg-black/50 px-2 py-0.5 text-[10px] text-white backdrop-blur-sm">
              ▶
            </span>
          </Link>
        );
      })}
      {isFetchingNextPage && (
        <div className="col-span-3 py-4">
          <PageLoader className="min-h-[80px]" />
        </div>
      )}
    </div>
  );
}
