"use client";

import React, { useEffect, useState } from "react";
import { useInfiniteQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { fetchPosts } from "@/api/fetchPosts";
import { Post, User } from "@/types/types";
import axios from "axios";
import { BASE_URL, IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import Image from "next/image";
import BoldIcon from "@/components/ui/BoldIcon";
import { ChatListSkeleton } from "@/components/ui/ChatSkeletons";
import PageLoader from "@/components/ui/PageLoader";

interface InfinitePostsProps {
  token: string;
  _id: string;
  filters: {
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
  };
}

function ModelContentPosts({ filters, token, _id }: InfinitePostsProps) {
  const router = useRouter();
  const [allUsers, setAllUsers] = useState<User[]>([]);

  const fetchUsers = async () => {
    try {
      const response = await axios.get(`${BASE_URL}/users?limit=1000`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response?.data?.users) {
        setAllUsers(response.data.users);
      }
    } catch (err) {
      console.error("خطا در دریافت کاربران:", err);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const { data, isFetchingNextPage, isLoading, isError } = useInfiniteQuery({
    queryKey: ["posts", filters, _id],
    queryFn: ({ pageParam = 1 }) =>
      fetchPosts(pageParam as number, 9999, { ...filters, _id }, token),
    getNextPageParam: (lastPage, allPages) =>
      lastPage.posts.length > 0 ? allPages.length + 1 : undefined,
    initialPageParam: 1,
    refetchOnWindowFocus: false,
  });

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

  const filteredPosts = posts.filter((post) => {
    const user = allUsers.find((u) => u._id === post.userId);
    if (!user) return true;

    let include = true;
    if (filters.province && user.province?.id)
      include &&= String(user.province.id) === filters.province;
    if (filters.city && user.city?.id)
      include &&= String(user.city.id) === filters.city;
    if (filters.expertise && user.sub_expertise)
      include &&= user.sub_expertise.includes(filters.expertise);
    if (filters.userLevel) include &&= user.user_type === filters.userLevel;
    if (filters.rateFilter) include &&= String(post.rate) === filters.rateFilter;
    return include;
  });

  const openPost = (post: Post) => {
    router.push(`/posts/${post._id}?userId=${_id}`);
  };

  if (isLoading) return <ChatListSkeleton count={6} />;

  if (isError)
    return <p className="text-center mt-4 text-red-500">خطایی رخ داده است.</p>;

  if (filteredPosts.length === 0)
    return <p className="text-center mt-4">هیچ پستی یافت نشد.</p>;

  return (
    <div className="flex flex-col gap-1 p-1">
      <div className="grid grid-cols-3 gap-0.5 sm:gap-1">
        {filteredPosts.map((post) => {
          const mediaFiles =
            post.files?.map((file) => ({
              ...file,
              src: buildStorageUrl(file.path),
            })) || [];

          const firstMedia = mediaFiles[0]?.src || "/images/placeholder.png";

          return (
            <button
              type="button"
              key={post._id}
              className="relative aspect-square cursor-pointer overflow-hidden rounded-md sm:rounded-xl group focus:outline-none focus-visible:ring-2 focus-visible:ring-pink-500"
              onClick={() => openPost(post)}
              aria-label="مشاهده پست"
            >
              {post.type === "image" ? (
                <Image
                  src={firstMedia}
                  alt={post.caption || `پست ${post._id}`}
                  width={300}
                  height={300}
                  className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105 group-active:scale-100"
                  loading="lazy"
                  unoptimized
                />
              ) : (
                <video
                  src={firstMedia}
                  className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                  muted
                  playsInline
                  preload="metadata"
                />
              )}
              {post.type === "video" && (
                <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
                  <div className="rounded-full bg-black/40 p-2">
                    <BoldIcon name="play" size={18} tinted className="text-white" />
                  </div>
                </div>
              )}
            </button>
          );
        })}
      </div>
      {isFetchingNextPage && <PageLoader className="py-4" />}
    </div>
  );
}

export default ModelContentPosts;
