"use client";

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

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

function ModelContentPosts({
  filters,
  token,
  _id,
  privateLocked = false,
}: InfinitePostsProps) {
  const { t } = useTranslation("common");
  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 filterKey = useMemo(() => JSON.stringify({ ...filters, _id }), [filters, _id]);

  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,
    enabled: !privateLocked,
  });

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

  const openPost = useCallback(
    (post: Post) => {
      cacheReelsSeedPost(post);
      navigateWithSavedScroll(
        router,
        scrollKey,
        `${buildPostPath(post._id, post)}?userId=${_id}&feed=user`
      );
    },
    [router, scrollKey, _id]
  );

  if (privateLocked) {
    return (
      <div className="mt-6 flex flex-col items-center px-6 py-10 text-center">
        <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full border-2 border-neutral-300 text-2xl dark:border-neutral-700">
          🔒
        </div>
        <p className="text-sm font-bold text-foreground">{t("models.privateAccount")}</p>
        <p className="mt-2 max-w-xs text-xs text-neutral-500">
          {t("models.privateAccountHint")}
        </p>
      </div>
    );
  }

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

  if (isError)
    return <p className="text-center mt-4 text-red-500">{t("models.loadError")}</p>;

  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;
  });

  if (filteredPosts.length === 0)
    return <p className="text-center mt-4">{t("models.noPosts")}</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";
          const poster =
            post.post_images?.[0] ||
            mediaFiles.find((f) => f.type === "image")?.src;

          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={t("models.viewPost")}
            >
              {post.type === "image" ? (
                <Image
                  src={firstMedia}
                  alt={post.caption || t("models.postAlt", { id: 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
                />
              ) : poster ? (
                <Image
                  src={
                    typeof poster === "string" && poster.startsWith("http")
                      ? poster
                      : buildStorageUrl(String(poster))
                  }
                  alt={post.caption || t("models.postAlt", { id: 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>
              )}
              {post.is_pinned ? (
                <span
                  className="pointer-events-none absolute left-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white backdrop-blur-sm"
                  title={t("posts.pinnedBadge")}
                  aria-label={t("posts.pinnedBadge")}
                >
                  <BoldIcon name="bookmark" size={14} tinted className="text-white" />
                </span>
              ) : null}
              <span className="pointer-events-none absolute bottom-1.5 right-1.5 flex items-center gap-0.5 rounded-md bg-black/55 px-1.5 py-0.5 text-[10px] font-semibold text-white backdrop-blur-sm">
                <BoldIcon name="eye" size={11} tinted className="text-white" />
                {formatViewCount(post.viewsCount ?? 0)}
              </span>
            </button>
          );
        })}
      </div>
      {isFetchingNextPage && <PageLoader className="py-4" />}
    </div>
  );
}

export default ModelContentPosts;
