"use client";

import React, { useEffect, useCallback, useMemo } from "react";
import { navigateWithSavedScroll } from "@/lib/listScrollRestoration";
import { useListScrollRestoration } from "@/hooks/useListScrollRestoration";
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";
import { buildPostPath } from "@/lib/postSlug";
import { useTranslation } from "react-i18next";

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

interface PageData {
  posts: Post[];
}

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

  const filterKey = useMemo(
    () => JSON.stringify({ ...filters, type: typeFilter }),
    [filters, typeFilter]
  );

  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" },
        token
      ),
    getNextPageParam: (lastPage, allPages) =>
      lastPage.posts.length > 0 ? allPages.length + 1 : undefined,
    initialPageParam: 1,
    refetchOnWindowFocus: false,
  });

  const scrollKey = useListScrollRestoration(
    "posts",
    { f: filterKey },
    !isLoading
  );

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

  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">
        {[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">
        {t("posts.loadError")}: {error?.message || t("posts.retry")}
      </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" || post.status === "temp_accept") &&
      matchesType &&
      matchesHashtag
    );
  });

  return (
      <div className="mt-0 mb-24 divide-y divide-neutral-200/70 dark:divide-neutral-800/80">
      {posts.length === 0 ? (
        <p className="py-12 text-center text-sm text-neutral-500">
          {t("posts.empty")}
        </p>
      ) : null}
      {posts.map((post) => (
        <MainModelCard
          key={post._id}
          postData={post}
          onMediaClick={() => openPostInReels(post)}
        />
      ))}
        {isFetchingNextPage && (
          <PageLoader className="min-h-[120px]" />
        )}
    </div>
  );
}
