"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import { useGetBookmarkPostListQuery } from "../store/api/BookmarkPostList";
import Cookies from "js-cookie";
import useApiPost from "../hooks/postData";
import toast from "react-hot-toast";
import { useGetAllPostReelsQuery } from "../store/api/GetAllPostReel";
import NoPostGif from "../../../public/assets/NoPost.png";
import ReelDetail from "../Explore/Reel_Comment";
import PostDetail from "../Explore/Post_Detail";
import NoSavedBookmark from "../../../public/assets/NoSavedBookmark.png";
import NoBookmarkd from "../../../public/assets/NoBookmarkd.png";
import { ClipLoader } from "react-spinners";
import { MdOutlineArrowBackIos } from "react-icons/md";
import TextTranslate from "../utils/TextTranslate";
import { FiHeart, FiMessageCircle, FiChevronLeft, FiChevronRight } from "react-icons/fi";
import { showSuccessToast } from "../components/Toast/SuccessToast";
import { showErrorToast } from "../components/Toast/ErrorToast";

interface Props {
  onBack: () => void;
}
const SavedBookmark: React.FC<Props> = ({ onBack }) => {
  const token = Cookies.get("Snapta_auth_token");
  const {
    data: BookmarkData,
    refetch,
    isLoading,
  } = useGetBookmarkPostListQuery({ token: token || "" });
  
  const { data, loading, error, postData } = useApiPost();
  
  useEffect(() => {
    refetch();
  }, [refetch]);

  const BookmarkList = BookmarkData?.bookmark_post_list || [];

  const handleRemoveBookmark = async (postId: string, postType: string) => {
    // ✅ Optimistically remove from UI
    setLocalBookmarks((prev) =>
      prev.filter((item) => item.post_id !== postId)
    );

    try {
      const response = await postData("/bookmark_post", {
        post_id: postId,
        type: postType,
      });

      showSuccessToast(response?.message);
    } catch (error: any) {
      showErrorToast("Failed to remove bookmark",  "Something went wrong.");
      // ❌ Rollback if API fails
      refetch();
    }
  };
  
  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
  } | null>(null);
  
  const handleVideoClick = (postId: string, url: string) => {
    setSelectedVideo({ postId, url });
  };

  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);
  
  const handleImageClick = (postId: string, images: string[]) => {
    setSelectedPost({ postId, images });
  };
  
  const [localBookmarks, setLocalBookmarks] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState<number | null>(null);
  
  useEffect(() => {
    if (BookmarkData?.bookmark_post_list) {
      setLocalBookmarks(BookmarkData.bookmark_post_list);
    }
  }, [BookmarkData]);

  // Create items array for modal navigation
  const items = localBookmarks.map((b) => ({
    id: b.post_id,
    type: b.post_videos.length > 0 ? "reel" : "image",
    src: b.post_videos.length > 0 
      ? b.post_videos[0].post_video_thumbnail 
      : (b.post_images[0]?.url || ""),
    images: b.post_images.map((i: any) => i.url),
    videoUrl: b.post_videos[0]?.url,
    total_likes: b.total_like ?? b.total_likes ?? 0,
    total_comments: b.total_comment ?? b.total_comments ?? 0,
  }));

  const currentItem = currentIndex !== null ? items[currentIndex] : null;

  const goNext = () => {
    if (currentIndex !== null && currentIndex < items.length - 1) {
      setCurrentIndex(currentIndex + 1);
    }
  };

  const goPrev = () => {
    if (currentIndex !== null && 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]);

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

  return (
    <>
      {isLoading ? (
        <div className="flex justify-center items-center h-[80vh]">
          <ClipLoader
            loading={isLoading}
            size={25}
            color="var(--text-primary)"
          />
        </div>
      ) : (
        <div className="bg-[var(--bg-primary)] rounded-lg h-auto lg:w-[90%] 2xl:w-[70%] w-[95%] mx-auto">
          {/* Header */}
          <div className="flex gap-2 px-1 lg:px-2 items-center mt-4 sm:mt-0">
            <div onClick={onBack} className="cursor-pointer flex items-center gap-2">
              <MdOutlineArrowBackIos className="text-[var(--text-primary)] sm:hidden block" />
              <h2 className="font-gilroy_semibold text-[19px] font-semibold text-[var(--text-primary)]">
                <TextTranslate text="Saved Bookmark"/>
              </h2>
            </div>
          </div>

          {localBookmarks.length > 0 ? (
            <div className="p-2 ">
              {/* Responsive Grid: 1 col mobile, 2 cols md, 3 cols lg */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-[0.05px]">
                {localBookmarks.map((b, idx) => {
                  const media =
                    b.post_images.length > 0
                      ? b.post_images[0].url
                      : b.post_videos.length > 0
                      ? b.post_videos[0].post_video_thumbnail
                      : null;

                  const totalLikes = b.total_like ?? b.total_likes ?? 0;
                  const totalComments = b.total_comment ?? b.total_comments ?? 0;

                  return (
                    <div
                      key={b.bookmark_post_id}
                      className="relative w-full aspect-[3/4] rounded-[5px] overflow-hidden cursor-pointer group border border-[var(--border-color)]"
                      onClick={() => handleItemClick(idx)}
                    >
                      {media ? (
                        b.post_videos.length > 0 ? (
                          <div className="w-full h-full relative">
                            <img
                              src={media}
                              alt="thumbnail"
                              className="w-full h-full object-cover"
                            />
                            <div className="absolute inset-0 flex justify-center items-center transition pointer-events-none">
                              <div className="p-3 bg-black/20 backdrop-blur-md rounded-full">
                                <Image
                                  src={"/assets/play.png"}
                                  alt="play"
                                  height={18}
                                  width={18}
                                />
                              </div>
                            </div>
                          </div>
                        ) : (
                          <img
                            src={media}
                            alt="post"
                            className="w-full h-full object-cover"
                          />
                        )
                      ) : (
                        <div className="w-full h-full bg-gray-100 flex items-center justify-center text-[var(--text-secondary)]">
                          <span>No Media</span>
                        </div>
                      )}

                      {/* Hover Overlay with Like and Comment Counts */}
                      <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 pointer-events-none z-10">
                        <div className="flex items-center gap-1 text-white">
                          <FiHeart size={26} fill="white" />
                          <span className="font-bold text-lg">{totalLikes}</span>
                        </div>
                        <div className="flex items-center gap-1 text-white">
                          <FiMessageCircle size={26} fill="white" />
                          <span className="font-bold text-lg">{totalComments}</span>
                        </div>
                      </div>

                      {/* Bookmark Icon */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleRemoveBookmark(b.post_id, b.type);
                        }}
                       className="absolute top-3 right-3 p-1.5 rounded-full bg-white/25 opacity-100 transition-opacity duration-200 z-20 hover:scale-110"
                      >
                        <img
                          src="/assets/filled_save.png"
                          alt="remove"
                          className="w-[18px] h-[18px] invert img-theme"
                        />
                      </button>

                      {/* Reel Icon for video posts */}
                      {b.post_videos.length > 0 && (
                        <div className="absolute top-3 left-3 z-10 pointer-events-none">
                          <img 
                            src="/assets/reel_icon.png" 
                            alt="reel_icon" 
                            className="w-5 h-5 invert brightness-200" 
                          />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ) : (
            <div className="flex flex-col justify-center items-center h-full py-20">
              {/* Light Mode Image - Hidden when 'dark' class is present */}
              <Image
                src={NoSavedBookmark}
                alt="No bookmarks"
                className="w-56 h-56 block dark:hidden"
              />
              {/* Dark Mode Image - Shown ONLY when 'dark' class is present */}
              <Image
                src={NoBookmarkd}
                alt="No bookmarks"
                className="w-56 h-56 hidden dark:block"
              />
              <p className="mt-4 text-[var(--text-secondary)] font-gilroy_md">
                <TextTranslate text="No saved items found" />
              </p>
            </div>
          )}

         {/* Modal with Prev/Next Navigation */}
{currentItem && (
  <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm">
    {/* LEFT BUTTON */}
    {currentIndex !== null && currentIndex > 0 && (
      <button
        onClick={(e) => { e.stopPropagation(); goPrev(); }}
        className="absolute left-3 sm: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-2 sm:p-4 rounded-full transition-all hover:scale-110"
      >
        <FiChevronLeft size={24} className="sm:size-[32px] pr-0 sm:pr-1" />
      </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
          images={currentItem.images || [currentItem.src]}
          postId={currentItem.id}
          onClose={() => setCurrentIndex(null)}
        />
      ) : (
        <ReelDetail
                        videoSrc={currentItem.videoUrl || currentItem.src}
                        postId={currentItem.id}
                        onClose={() => setCurrentIndex(null)} isMuted={false} onMuteToggle={function (isMuted: boolean): void {
                          throw new Error("Function not implemented.");
                        } } onCommentSuccess={function (): void {
                          throw new Error("Function not implemented.");
                        } }        />
      )}
    </div>

    {/* RIGHT BUTTON */}
    {currentIndex !== null && currentIndex < items.length - 1 && (
      <button
        onClick={(e) => { e.stopPropagation(); goNext(); }}
        className="absolute right-3 sm: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-2 sm:p-4 rounded-full transition-all hover:scale-110"
      >
        <FiChevronRight size={24} className="sm:size-[32px] pl-0 sm:pl-1" />
      </button>
    )}
  </div>
)}
        </div>
      )}
    </>
  );
}

export default SavedBookmark;