"use client";
import React, { useEffect, useState } from "react";
import { Skeleton } from "@mui/material";
import InfiniteScroll from "react-infinite-scroll-component";
import useApiPost from "../hooks/postData";
import PostDetail from "./Post_Detail";
import ReelDetail from "./Reel_Comment";
import Image from "next/image";
import SearchBox from "../Search/ExploreSearch";
import TextTranslate from "../utils/TextTranslate";
import { FiHeart, FiMessageCircle, FiChevronLeft, FiChevronRight } from "react-icons/fi";

type ItemType = {
  id: string;
  type: "reel" | "image";
  src: string; 
  images?: string[]; 
  total_likes?: string | number;
  total_comments?: string | number;
};

const ReelImagePattern = () => {
  const [items, setItems] = useState<ItemType[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const { postData } = useApiPost();
  const [currentIndex, setCurrentIndex] = useState<number | null>(null);
  const currentItem = currentIndex !== null ? items[currentIndex] : null;

  // Pagination Fix: Fetch more if at the end of the list
  const goNext = () => {
    if (currentIndex === null) return;
    if (currentIndex < items.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else if (hasMore && !isFetchingMore) {
      // If at the last item, try to fetch more and then move to next
      fetchData(page).then(() => {
         setCurrentIndex(currentIndex + 1);
      });
    }
  };

  const goPrev = () => {
    if (currentIndex === null) return;
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (currentIndex === null) return;
      if (e.key === "ArrowRight") {
        goNext();
      } else if (e.key === "ArrowLeft") {
        goPrev();
      } else if (e.key === "Escape") {
        setCurrentIndex(null);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [currentIndex, items.length]); // Added dependency

  const handleItemClick = (index: number) => {
    setCurrentIndex(index);
  };

  useEffect(() => {
    fetchData(1, true);
  }, []);

  const fetchData = async (pageNo: number, initial = false) => {
    try {
      if (!initial) setIsFetchingMore(true);
      const response = await postData("/get_all_reels_datainshow", {
        page_no: pageNo,
      });
      const parsed: ItemType[] = (response.recent_content || [])
        .map((item: any) => {
          const allImages =
            item?.post_image?.map((img: any) => img.url).filter(Boolean) || [];
          return {
            id: String(item.post_id),
            type: item.post_type === "reel" ? "reel" : "image",
            src:
              item.post_type === "reel"
                ? item.post_videos?.[0]?.url || allImages[0]
                : allImages[0],
            images: allImages,
            total_likes: item.total_like ?? item.total_likes ?? 0,
            total_comments: item.total_comment ?? item.total_comments ?? 0,
          };
        })
        .filter((item: any) => item.src);
      
      if (initial) {
        setItems(parsed);
      } else {
        setItems((prev) => [...prev, ...parsed]);
      }
      setHasMore(parsed.length > 0);
      setPage(pageNo + 1);
    } catch (error) {
      console.error("Fetching error:", error);
      setHasMore(false);
    } finally {
      if (initial) setIsInitialLoading(false);
      setIsFetchingMore(false);
    }
  };

  // Layout Logic (Maintains your specific zig-zag pattern)
  const reels = items.filter((i) => i.type === "reel");
  const images = [...items.filter((i) => i.type === "image")];
  let layout: { col1: ItemType[]; col2: ItemType[]; col3: ItemType[] } = {
    col1: [], col2: [], col3: [],
  };
  let colHeights = { col1: 0, col2: 0, col3: 0 };
  let reelIndex = 0;
  let totalRows = Math.ceil(items.length / 3);

  for (let row = 1; row <= totalRows; row++) {
    if (row % 2 === 1) {
      if (reelIndex < reels.length) {
        layout.col1.push(reels[reelIndex]);
        colHeights.col1 += 600;
        reelIndex++;
      }
      ["col2", "col3"].forEach((col) => {
        if (images.length) {
          const img = images.shift()!;
          layout[col as keyof typeof layout].push(img);
          colHeights[col as keyof typeof colHeights] += 400;
        }
      });
    } else {
      if (reelIndex < reels.length) {
        layout.col3.push(reels[reelIndex]);
        colHeights.col3 += 600;
        reelIndex++;
      }
      ["col1", "col2"].forEach((col) => {
        if (images.length) {
          const img = images.shift()!;
          layout[col as keyof typeof layout].push(img);
          colHeights[col as keyof typeof colHeights] += 400;
        }
      });
    }
  }

  const renderItem = (item: ItemType) => (
    <div
      key={item.id}
      className={`relative overflow-hidden rounded mb-[2px] group cursor-pointer ${
        item.type === "reel" ? "sm:h-[500px]" : "sm:h-[300px] md:h-[350px] h-[calc(100vw/3)]"
      }`}
      onClick={() => handleItemClick(items.findIndex(i => i.id === item.id))}
    >
      {item.type === "reel" ? (
        <video autoPlay muted loop src={item.src} className="w-full h-full object-cover rounded" />
      ) : (
        <img src={item.src} alt="post" className="w-full h-full object-cover rounded" />
      )}
      <div className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-6 z-20">
        <div className="flex items-center gap-1 text-white">
          <FiHeart size={26} fill="white" />
          <span className="font-bold text-lg">{item.total_likes}</span>
        </div>
        <div className="flex items-center gap-1 text-white">
          <FiMessageCircle size={26} fill="white" />
          <span className="font-bold text-lg">{item.total_comments}</span>
        </div>
      </div>
      {item.type === "reel" && (
        <div className="absolute top-3 right-3 z-10">
          <img src="/assets/reel_icon.png" alt="reel_icon" className="w-5 h-5 invert brightness-200" />
        </div>
      )}
    </div>
  );

  const renderShimmerColumn = () => (
    <>
      {[...Array(3)].map((_, i) => (
        <Skeleton key={i} variant="rectangular" height={i % 2 === 0 ? 600 : 400} sx={{ borderRadius: 2, mb: 2, bgcolor: 'var(--bg-secondary)' }} />
      ))}
    </>
  );

  return (
    <>
      <div className="2xl:hidden block z-50 bg-[var(--bg-primary)] mb-6">
        <SearchBox />
      </div>
    
      <div className="sm:p-4 bg-[var(--bg-primary)] min-h-screen">
        <h2 className="font-gilroy_semibold text-[20px] font-bold hidden sm:block  text-left text-[var(--text-primary)] mb-2.5">
                      <TextTranslate text="Explore "/>
                    </h2>
        {isInitialLoading ? (
          <div className="grid grid-cols-3 gap-[2px]">
            <div>{renderShimmerColumn()}</div>
            <div>{renderShimmerColumn()}</div>
            <div>{renderShimmerColumn()}</div>
          </div>
        ) : items.length === 0 ? (
          <div className="flex flex-col items-center justify-center min-h-[60vh]">
            <img src="/assets/NoPost.png" className="w-16 h-16 opacity-50 invert brightness-200" />
            <h2 className="text-lg font-semibold text-[var(--text-secondary)] mt-4">
              <TextTranslate text="No Reels or Images" />
            </h2>
          </div>
        ) : (
          <InfiniteScroll dataLength={items.length} next={() => fetchData(page)} hasMore={hasMore} loader={null}>
            <div className="grid grid-cols-3 gap-[2px]">
              <div>{layout.col1.map(renderItem)} {isFetchingMore && renderShimmerColumn()}</div>
              <div>{layout.col2.map(renderItem)} {isFetchingMore && renderShimmerColumn()}</div>
              <div>{layout.col3.map(renderItem)} {isFetchingMore && renderShimmerColumn()}</div>
            </div>
          </InfiniteScroll>
        )}
      </div>

      {currentItem && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm">
          {/* LEFT BUTTON - Positioned to be visible above everything */}
          {currentIndex !== null && currentIndex > 0 && (
            <button
              onClick={(e) => { e.stopPropagation(); goPrev(); }}
              className="absolute left-6 top-1/2 -translate-y-1/2 z-[110] bg-black/30 hover:bg-black/40 dark:bg-white/30 dark:hover:bg-white/40 text-white p-4 rounded-full "
            >
              <FiChevronLeft size={30} />
            </button>
          )}

          {/* MAIN MODAL CONTENT */}
          <div className="w-full h-full flex items-center justify-center p-4" onClick={(e) => e.stopPropagation()}>
            {currentItem.type === "image" ? (
              <PostDetail
                imageSrc={currentItem.images?.[0] || currentItem.src}
                images={currentItem.images || [currentItem.src]}
                postId={currentItem.id}
                onClose={() => setCurrentIndex(null)}
              />
            ) : (
              <ReelDetail
                videoSrc={currentItem.src}
                postId={currentItem.id}
                onClose={() => setCurrentIndex(null)}
              />
            )}
          </div>

          {/* RIGHT BUTTON */}
          {(currentIndex !== null && (currentIndex < items.length - 1 || hasMore)) && (
            <button
              onClick={(e) => { e.stopPropagation(); goNext(); }}
              className="absolute right-6 top-1/2 -translate-y-1/2 z-[110] bg-black/30 hover:bg-black/40 dark:bg-white/30 dark:hover:bg-white/40 text-white p-4 rounded-full "
            >
              <FiChevronRight size={30} />
            </button>
          )}
        </div>
      )}
    </>
  );
};

export default ReelImagePattern;