"use client";

import React, { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useInfiniteQuery } from "@tanstack/react-query";
import { fetchPosts } from "@/api/fetchPosts";
import { fetchPostById } from "@/api/fetchPostById";
import { Post } from "@/types/types";
import MainModelCard from "@/components/models/MainModelCard/MainModelCard";
import { MutedProvider } from "@/components/models/ModelPage/MainModelCardPost";
import PageLoader from "@/components/ui/PageLoader";
import { Skeleton } from "@/components/ui/skeleton";
import Cookies from "js-cookie";
import { FiX } from "react-icons/fi";

interface PostFeedViewProps {
  initialPostId: string;
  userId?: string;
  showClose?: boolean;
  videoOnly?: boolean;
}

export default function PostFeedView({
  initialPostId,
  userId: userIdProp,
  showClose = true,
  videoOnly = false,
}: PostFeedViewProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const userIdFromQuery = searchParams.get("userId") || "";
  const token = Cookies.get("token") || "";
  const scrollRef = useRef<HTMLDivElement>(null);
  const scrolledRef = useRef(false);

  const [resolvedUserId, setResolvedUserId] = useState(
    userIdProp || userIdFromQuery || ""
  );

  useEffect(() => {
    if (userIdProp || userIdFromQuery) {
      setResolvedUserId(userIdProp || userIdFromQuery);
      return;
    }
    fetchPostById(initialPostId).then((post) => {
      const uid = post?.userId || post?.user_id;
      if (uid) setResolvedUserId(uid);
    });
  }, [initialPostId, userIdProp, userIdFromQuery]);

  const { data, isLoading, isError } = useInfiniteQuery({
    queryKey: ["post-feed", resolvedUserId, initialPostId, videoOnly],
    queryFn: ({ pageParam = 1 }) =>
      fetchPosts(
        pageParam as number,
        20,
        {
          _id: resolvedUserId,
          ...(videoOnly ? { type: "video" } : {}),
        },
        token
      ),
    initialPageParam: 1,
    getNextPageParam: (lastPage, pages) =>
      lastPage.posts?.length ? pages.length + 1 : undefined,
    enabled: !!resolvedUserId || !!token,
  });

  const posts: Post[] =
    data?.pages
      ?.flatMap((p) => p.posts)
      ?.filter(
        (p) =>
          p.status === "accept" && (!videoOnly || p.type === "video")
      ) ?? [];

  useEffect(() => {
    if (scrolledRef.current || !posts.length || !scrollRef.current) return;
    const idx = posts.findIndex((p) => p._id === initialPostId);
    const targetIdx = idx >= 0 ? idx : 0;
    scrollRef.current.scrollTo({
      top: targetIdx * window.innerHeight,
      behavior: "auto",
    });
    scrolledRef.current = true;
  }, [posts, initialPostId]);

  if (!resolvedUserId && isLoading) {
    return (
      <div className="space-y-4 p-4">
        <Skeleton className="h-[70vh] w-full rounded-2xl" />
      </div>
    );
  }

  if (isError || posts.length === 0) {
    return (
      <p className="py-20 text-center text-neutral-500">پست یافت نشد.</p>
    );
  }

  return (
    <MutedProvider>
      <div className="relative min-h-[100dvh] bg-background">
        {showClose && (
          <button
            type="button"
            onClick={() => router.back()}
            className="gentle-transition fixed left-4 top-[calc(1rem+env(safe-area-inset-top))] z-[100] flex h-10 w-10 items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-md active:scale-90"
            aria-label="بستن"
          >
            <FiX size={22} />
          </button>
        )}
        <div
          ref={scrollRef}
          className="h-[100dvh] snap-y snap-mandatory overflow-y-auto scroll-smooth"
        >
          {posts.map((post) => (
            <article
              key={post._id}
              id={`post-${post._id}`}
              className="flex min-h-[100dvh] snap-start items-start justify-center py-2"
            >
              <div className="w-full max-w-2xl px-2 sm:px-4">
                <MainModelCard postData={post} />
              </div>
            </article>
          ))}
        </div>
      </div>
    </MutedProvider>
  );
}
