"use client";
import React, { useRef, useState, useCallback, useEffect } from "react";
import Image from "next/image";
import useApiPost from "@/app/hooks/postData";
import { Post } from "@/app/types/AllPost";
import NoPostGif from "../../../../public/assets/NoPost.png";
import ShimmerPost from "./ShimmerPost";
import PostDetail from "../../Explore/Post_Detail";
import ReelDetail from "../../Explore/Reel_Comment";
import { useAppSelector } from "@/app/hooks/hooks";

function SecondUserAllPost() {
  const { postData } = useApiPost();
  const [pageNo, setPageNo] = useState(1);
  const [AllPosts, setAllPosts] = useState<Post[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const hasFetchedPageOneRef = useRef(false);
  
  // Logic updated to pull targetUserId from viewedUser slice
  const targetUserId = useAppSelector((state) => state.viewedUser.viewedUserId);

  // Main Fetch Effect
  useEffect(() => {
    if (!targetUserId) return;

    let isMounted = true;

    const fetchPosts = async () => {
      if (!hasMore || (isLoadingMore && pageNo !== 1)) return;
      if (pageNo === 1 && hasFetchedPageOneRef.current) return;

      if (pageNo === 1) hasFetchedPageOneRef.current = true;

      try {
        setIsLoadingMore(true);

        const response = await postData("/second_user_all_post_pagination", {
          to_user_id: targetUserId, // Using targetUserId here
          page_no: pageNo,
        });

        const newPosts: Post[] = response?.post || [];

        if (isMounted) {
          setAllPosts((prev) => (pageNo === 1 ? newPosts : [...prev, ...newPosts]));
          setHasMore(newPosts.length > 0);
        }
      } catch (error) {
        console.error("Error fetching paginated posts:", error);
      } finally {
        if (isMounted) {
          setIsLoadingMore(false);
          if (pageNo === 1) setIsInitialLoading(false);
        }
      }
    };

    fetchPosts();

    return () => {
      isMounted = false;
    };
  }, [pageNo, targetUserId]); // Depend on targetUserId

  // Reset when a new user is selected (profile navigation)
  useEffect(() => {
    setPageNo(1);
    setAllPosts([]);
    setHasMore(true);
    setIsInitialLoading(true);
    hasFetchedPageOneRef.current = false;
  }, [targetUserId]);

  const observer = useRef<IntersectionObserver | null>(null);
  const lastPostRef = useCallback(
    (node: HTMLDivElement | null) => {
      if (isLoadingMore) return;
      if (observer.current) observer.current.disconnect();

      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          setPageNo((prevPageNo) => prevPageNo + 1);
        }
      });

      if (node) observer.current.observe(node);
    },
    [isLoadingMore, hasMore]
  );

  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);

  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
  } | null>(null);

  const extractValidUrl = (url: string): string => {
    return url.includes("https://") ? "https://" + url.split("https://").pop() : url;
  };

  const handleImageClick = (postId: string, images: { url: string }[]) => {
    const imageUrls = images.map((img) => extractValidUrl(img.url));
    setSelectedPost({ postId, images: imageUrls });
  };

  const handleVideoClick = (postId: string, url: string) => {
    setSelectedVideo({ postId, url });
  };

  return (
    <>
      <div className="w-full sm:w-[1050px] mx-auto min-h-screen">
        <div className="flex flex-col items-center w-full">
          {isInitialLoading ? (
            <div className="w-full transition-opacity duration-300">
              <ShimmerPost />
            </div>
          ) : AllPosts.length > 0 ? (
            <div className="w-full animate-in fade-in duration-500">
              <div className="grid grid-cols-3 gap-[1px] sm:gap-1 w-full">
                {AllPosts.map((post, index) => {
                  const firstMedia = post.image?.[0];
                  if (!firstMedia) return null;

                  const isLastPost = index === AllPosts.length - 1;

                  return (
                    <div
                      key={`${post.post_id}-${index}`}
                      className="w-full aspect-square relative overflow-hidden bg-[var(--bg-secondary)]"
                      ref={isLastPost ? lastPostRef : null}
                    >
                      <button
                        className="w-full h-full block group"
                        onClick={() => {
                          if (firstMedia.type === "video") {
                            handleVideoClick(post.post_id, firstMedia.url);
                          } else {
                            handleImageClick(
                              post.post_id,
                              post.image.map((i) => ({
                                url: i.url,
                                type: i.type,
                              }))
                            );
                          }
                        }}
                      >
                        {firstMedia.type === "video" ? (
                          <>
                            <video
                              src={firstMedia.url}
                              className="w-full h-full object-cover"
                              muted
                              autoPlay
                              loop
                            />
                            <Image
                              src="/assets/reel_icon.png"
                              alt="reel_icon"
                              height={28}
                              width={28}
                              className="absolute top-2 right-2 w-5 h-5 z-20"
                            />

                            <div className="flex gap-1 items-center absolute bottom-2 left-2 z-20">
                              <Image
                                src="/assets/reel_eye.png"
                                alt="reel eye"
                                height={24}
                                width={24}
                                className="w-4 h-4"
                              />
                              <p className="text-xs text-white font-gilroy_regular font-medium">
                                {post.total_view}
                              </p>
                            </div>
                          </>
                        ) : (
                          <img
                            src={extractValidUrl(firstMedia.url)}
                            alt={`post-${post.post_id}`}
                            className="w-full h-full object-cover"
                          />
                        )}
                        {post.image.length > 1 && (
                          <Image
                            src="/assets/Multiple_Post.png"
                            alt="multiple_post"
                            height={16}
                            width={16}
                            className="absolute top-2 right-2 w-4 h-4 z-20"
                          />
                        )}
                      </button>
                    </div>
                  );
                })}
              </div>
              
              {isLoadingMore && (
                <div className="w-full mt-2">
                  <ShimmerPost />
                </div>
              )}
            </div>
          ) : (
            <div className="flex flex-col justify-center items-center min-h-[400px] w-full">
              <Image
                src={NoPostGif}
                alt="No posts available"
                className="w-20 h-20 img-theme"
              />
              <span className="text-[var(--text-primary)] opacity-50 font-gilroy_md mt-4 ml-[25px]">
                No Post available
              </span>
            </div>
          )}
        </div>
      </div>

      {selectedPost && (
        <PostDetail
          imageSrc={selectedPost.images[0]}
          images={selectedPost.images}
          postId={selectedPost.postId}
          onClose={() => setSelectedPost(null)}
        />
      )}

      {selectedVideo && (
        <ReelDetail
          videoSrc={selectedVideo.url}
          postId={selectedVideo.postId}
          onClose={() => setSelectedVideo(null)}
        />
      )}
    </>
  );
}

export default SecondUserAllPost;