"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "../../hooks/hooks";
import useApiPost from "../../hooks/postData";
import ShimmerPost from "../../Profile/Post/ShimmerPost";
import NoPostGif from "../../../../public/assets/NoPost.png";
import PostDetail from "../../Explore/Post_Detail";
import ReelComment from "../../Explore/Reel_Comment";
import TextTranslate from "../../utils/TextTranslate";
import { FiHeart, FiMessageCircle, FiChevronLeft, FiChevronRight } from "react-icons/fi";
import { setHashtagName } from "../../store/Slice/hashtagIdSlice";

function HashtagPage() {
  const params = useParams();
  const dispatch = useAppDispatch();
  
  // Get hashtag name from URL params
  const hashtagname = params?.hashtagname as string;
  
  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
  } | null>(null);
  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);
  const [currentIndex, setCurrentIndex] = useState<number | null>(null);
  const [items, setItems] = useState<any[]>([]);

  const { postData, data, loading } = useApiPost();

  const getHashtagPost = async () => {
    if (!hashtagname) return;
    try {
      await postData("/get_hashtag_by_post", {
        hashtag: hashtagname,
      });
    } catch (error) {
      console.error("Hashtag fetch error", error);
    }
  };

// Update Redux when hashtag changes
  useEffect(() => {
    if (hashtagname) {
      dispatch(setHashtagName({ hashtagName: hashtagname }));
    }
  }, [hashtagname, dispatch]);

  useEffect(() => {
    if (hashtagname) {
      getHashtagPost();
    }
  }, [hashtagname]);

  useEffect(() => {
    if (data?.recent_content) {
      setItems(data.recent_content);
    }
  }, [data]);

  const HashtagPost = data?.recent_content;

  const handleImageClick = (postId: string, images: string[], index: number) => {
    setCurrentIndex(index);
    setSelectedPost({ postId, images });
    setSelectedVideo(null);
  };

  const handleVideoClick = (postId: string, url: string, index: number) => {
    setCurrentIndex(index);
    setSelectedVideo({ postId, url });
    setSelectedPost(null);
  };

  const goNext = () => {
    if (currentIndex === null) return;
    if (currentIndex < items.length - 1) {
      const nextItem = items[currentIndex + 1];
      if (nextItem.post_type === "image") {
        setSelectedPost({
          postId: nextItem.post_id,
          images: nextItem.post_image.map((img: any) => img.url),
        });
        setSelectedVideo(null);
      } else {
        setSelectedVideo({
          postId: nextItem.post_id,
          url: nextItem.post_videos?.[0]?.url || nextItem.post_image[0]?.url,
        });
        setSelectedPost(null);
      }
      setCurrentIndex(currentIndex + 1);
    }
  };

  const goPrev = () => {
    if (currentIndex === null) return;
    if (currentIndex > 0) {
      const prevItem = items[currentIndex - 1];
      if (prevItem.post_type === "image") {
        setSelectedPost({
          postId: prevItem.post_id,
          images: prevItem.post_image.map((img: any) => img.url),
        });
        setSelectedVideo(null);
      } else {
        setSelectedVideo({
          postId: prevItem.post_id,
          url: prevItem.post_videos?.[0]?.url || prevItem.post_image[0]?.url,
        });
        setSelectedPost(null);
      }
      setCurrentIndex(currentIndex - 1);
    }
  };

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (selectedPost || selectedVideo) {
        if (e.key === "ArrowRight") {
          goNext();
        } else if (e.key === "ArrowLeft") {
          goPrev();
        } else if (e.key === "Escape") {
          setSelectedPost(null);
          setSelectedVideo(null);
          setCurrentIndex(null);
        }
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [selectedPost, selectedVideo, currentIndex, items]);

  if (!hashtagname) {
    return (
      <div className="bg-[var(--bg-primary)] min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-[var(--text-secondary)] text-lg">No hashtag specified</p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-[var(--bg-primary)] min-h-screen transition-colors duration-300">
      <div className="pt-12 md:pt-0">
        {loading ? (
          <div className="px-4">
            <ShimmerPost />
          </div>
        ) : (
          <>
           <div className="flex justify-center w-full">
  <div className="w-full md:w-[665px] 2xl:w-[1050px] sm:w-[1050px] px-4 sm:px-0">
    <h2 className="sticky top-0 z-20 py-3 text-xl text-[var(--text-primary)] font-gilroy_bold font-bold bg-[var(--bg-primary)] border-b border-[var(--border-color)]">
      <span className="text-[var(--text-primary)]">#</span>
      <TextTranslate text={hashtagname} />
    </h2>
  </div>
</div>

            {HashtagPost && HashtagPost.length > 0 ? (
              <div className="flex justify-center w-full">
                <div className="grid grid-cols-3 gap-[1px] md:w-[665px] 2xl:w-[1050px] sm:w-[1050px] mx-4 sm:mx-0">
                  {HashtagPost.map((hashtag: any, index: number) => {
                    const totalLikes = hashtag.total_like ?? hashtag.total_likes ?? 0;
                    const totalComments = hashtag.total_comment ?? hashtag.total_comments ?? 0;
                    const isReel = hashtag.post_type === "reel";
                    const thumbnail = isReel
                      ? hashtag.post_image?.[0]?.post_video_thumbnail
                      : hashtag.post_image?.[0]?.url;
                    const videoUrl = hashtag.post_videos?.[0]?.url || hashtag.post_image?.[0]?.url;

                    return (
                      <div
                        key={index}
                        className="relative sm:h-[350px] h-[200px] w-full overflow-hidden group cursor-pointer"
                        onClick={() => {
                          if (isReel) {
                            handleVideoClick(hashtag.post_id, videoUrl, index);
                          } else {
                            handleImageClick(
                              hashtag.post_id,
                              hashtag.post_image.map((img: any) => img.url),
                              index
                            );
                          }
                        }}
                      >
                        {isReel ? (
                          <div className="w-full h-full relative">
                            <img
                              src={thumbnail}
                              className="w-full h-full object-cover transition-transform duration-500"
                              alt="video thumbnail"
                            />
                            <div className="absolute inset-0 flex justify-center items-center bg-black/10 transition-all group-hover:bg-black/50">
                              <div className="p-3 bg-white/20 backdrop-blur-md rounded-full shadow-lg transition-transform group-hover:scale-110">
                                <Image
                                  src={"/assets/play.png"}
                                  alt="play"
                                  height={18}
                                  width={18}
                                  className="invert img-theme"
                                />
                              </div>
                            </div>
                          </div>
                        ) : (
                          <img
                            alt="post"
                            className="w-full h-full object-cover transition-transform duration-500"
                            src={thumbnail}
                          />
                        )}

                        <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-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>

                        {isReel && (
                          <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 py-40 items-center text-center">
                  <Image
                                src={NoPostGif}
                                alt="No posts available"
                                className="w-16 h-16 opacity-20 img-theme"
                              />
                <p className="font-gilroy_md text-[var(--text-secondary)] mt-4 text-lg">
                  <TextTranslate text="No Hashtag Post" />
                </p>
              </div>
            )}
          </>
        )}
      </div>

      {/* Modal with Prev/Next Navigation */}
      {(selectedPost || selectedVideo) && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm">
          {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>
          )}

          <div className="w-full h-full flex items-center justify-center p-4" onClick={(e) => e.stopPropagation()}>
            {selectedPost ? (
              <PostDetail
             
                images={selectedPost.images}
                postId={selectedPost.postId}
                onClose={() => {
                  setSelectedPost(null);
                  setCurrentIndex(null);
                }}
              />
            ) : selectedVideo ? (
              <ReelComment
                                  videoSrc={selectedVideo.url}
                                  postId={selectedVideo.postId}
                                  onClose={() => {
                                      setSelectedVideo(null);
                                      setCurrentIndex(null);
                                  } } isMuted={false} onMuteToggle={function (isMuted: boolean): void {
                                      throw new Error("Function not implemented.");
                                  } } onCommentSuccess={function (): void {
                                      throw new Error("Function not implemented.");
                                  } }              />
            ) : null}
          </div>

          {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 HashtagPage;

