"use client";

import React, { useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useInfiniteQuery } from "@tanstack/react-query";
import MainModelCard from "@/components/models/MainModelCard/MainModelCard";
import { fetchPosts } from "@/api/fetchPosts";
import { Post } from "@/types/types";
import PageLoader from "@/components/ui/PageLoader";
import { Skeleton } from "@/components/ui/skeleton";
import { cacheReelsSeedPost } from "@/lib/reelsSeedPost";

interface InfinitePostsProps {
  token: string;
  filters: {
    hashtag?: string; // این خط را اضافه کن
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
    _id?: string;
  };
  typeFilter?: "image" | "video"; // فیلتر جدید برای نوع پست (تصویر یا ویدیو)
  type?: string; // فیلتر جدید برای نوع پست (تصویر یا ویدیو)
}

interface PageData {
  posts: Post[];
}

export default function InfinitePosts({
  filters,
  token,
  typeFilter,
}: InfinitePostsProps) {
  const router = useRouter();

  const openPostInReels = useCallback(
    (post: Post) => {
      cacheReelsSeedPost(post);
      const params = new URLSearchParams();
      params.set("feed", "home");
      Object.entries(filters).forEach(([key, value]) => {
        if (value) params.set(key, String(value));
      });
      router.push(`/posts/${post._id}?${params.toString()}`);
    },
    [filters, router]
  );

  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading,
    isError,
    error,
  } = useInfiniteQuery<PageData, Error>({
    queryKey: ["posts", { ...filters, type: typeFilter }],
    queryFn: ({ pageParam = 1 }) =>
      fetchPosts(
        pageParam as number,
        4,
        { ...filters, feedMode: "grid", sort: "latest" },
        token
      ),
    getNextPageParam: (lastPage, allPages) =>
      lastPage.posts.length > 0 ? allPages.length + 1 : undefined,
    initialPageParam: 1,
    refetchOnWindowFocus: false,
  });

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

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

  if (isLoading)
    return (
      <div className="mt-5 space-y-4 px-4">
        {[1, 2, 3].map((i) => (
          <Skeleton key={i} className="h-64 w-full rounded-2xl" />
        ))}
      </div>
    );

  if (isError)
    return (
      <p className="text-center mt-4 text-red-500">
        خطایی رخ داده است: {error?.message || "لطفاً دوباره تلاش کنید."}
      </p>
    );

  const allPosts: Post[] = data?.pages?.flatMap((page) => page.posts) ?? [];

  const posts = allPosts.filter((post) => {
    const matchesType = typeFilter ? post.type === typeFilter : true;
    // خط پایین اضافه شده برای هشتگ:
    const matchesHashtag = filters.hashtag ? post.caption?.includes(`#${filters.hashtag}`) : true;

    return post.status === "accept" && matchesType && matchesHashtag;
  });

  return (
    <div className="mt-5 space-y-4 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8  mb-24">
      {posts.map((post) => (
        <div key={post._id} className="space-y-2">
          <MainModelCard
            postData={post}
            onMediaClick={() => openPostInReels(post)}
          />
          <hr className="border-gray-200 dark:border-gray-700" />
        </div>
      ))}
        {isFetchingNextPage && (
          <PageLoader className="min-h-[120px]" />
        )}
    </div>
  );
}
