"use client";

import AddCard from "@/components/common/addCard/AddCard";
import { Post } from "@/interface/photo";
import fetcher from "@/utils/fetcher";
import Image from "next/image";
import useSWR from "swr";
import { useEffect, useRef, useState, useMemo } from "react";
import { IoChevronBack, IoChevronForward, IoClose, IoPause, IoPlay } from "react-icons/io5";
import { IoVolumeMute, IoVolumeHigh } from "react-icons/io5";
import AdsComponent from "@/components/common/googleAds/GoogleAds";


interface Ads {
  news_view_31: string;
  news_view_32: string;
}

interface ResponseData {
  posts: Post[];
  ads: Ads;
}

const PhotoGallery = () => {
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [isMuted, setIsMuted] = useState(true);
  const [selectedPostIndex, setSelectedPostIndex] = useState(0);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(true);
  const [videoDuration, setVideoDuration] = useState(5000);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const galleryRef = useRef<HTMLDivElement>(null);

  const adsSlot1 = "1431883232"
  const adsSlot2 = "8681432265"
  const adsSlot3 = "8974497186"
  const { data, error, isLoading } = useSWR<ResponseData>("/photo-post", fetcher);

  const { ads, posts = [] } = data || {};
  const validSelectedIndex = posts[selectedPostIndex] ? selectedPostIndex : 0;
  const totalImages = useMemo(() => posts[validSelectedIndex]?.media?.length || 0, [posts, validSelectedIndex]);

  useEffect(() => {
    const media = posts[validSelectedIndex]?.media?.[currentIndex];
    const isVideo = media?.video_url;

    let timer: NodeJS.Timeout;

    if (isPlaying && isPopupOpen) {
      if (isVideo) {
        timer = setTimeout(() => {
          setCurrentIndex((prevIndex) => (prevIndex + 1) % totalImages);
        }, videoDuration);
      } else {
        timer = setTimeout(() => {
          setCurrentIndex((prevIndex) => (prevIndex + 1) % totalImages);
        }, 5000);
      }
    }

    return () => clearTimeout(timer);
  }, [isPlaying, currentIndex, videoDuration, isPopupOpen, posts, validSelectedIndex, totalImages]);

  useEffect(() => {
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, []);

  const handleOpenPopup = (postIndex: number, index = 0) => {
    setSelectedPostIndex(postIndex);
    setCurrentIndex(index);
    setIsPopupOpen(true);
    setIsPlaying(true);
    document.body.style.overflow = 'hidden';
  };

  const handleClosePopup = () => {
    setIsPopupOpen(false);
    setIsPlaying(false);
    document.body.style.overflow = 'auto';
  };

  const handleNext = () => {
    setCurrentIndex((prevIndex) => (prevIndex + 1) % totalImages);
  };

  const handlePrev = () => {
    setCurrentIndex((prevIndex) => (prevIndex - 1 + totalImages) % totalImages);
  };

  const handleVideoLoad = () => {
    if (videoRef.current) {
      setVideoDuration(videoRef.current.duration * 1000);
    }
  };

  if (error) return <div>There was an Error!</div>;

  // useEffect(() => {
  //   if (videoRef.current) {
  //     setVideoDuration(videoRef.current.duration * 1000);
  //   }
  // }, [videoRef, posts, selectedPostIndex]);


  // const handleShare = (post: Post) => {
  //   const shareData = {
  //     title: post.title,
  //     text: post.media?.[currentIndex]?.description || post.title,
  //     url: `${window.location.origin}/post/${post.id}` // Adjust this URL as needed
  //   };

  //   if (navigator.share) {
  //     navigator.share(shareData)
  //       .catch(err => console.error('Error sharing:', err));
  //   } else {
  //     // Fallback for browsers that don't support Web Share API
  //     const shareUrl = `${window.location.origin}/post/${post.id}`;
  //     navigator.clipboard.writeText(shareUrl)
  //       .then(() => alert('Link copied to clipboard!'))
  //       .catch(err => console.error('Could not copy text: ', err));
  //   }
  // };

  return (
    <>
      {posts?.length > 0 && (
        <section className="mt-[20px]">
          <div className="container px-5 mx-auto">
            <div className="grid grid-cols-1 md:grid-cols-12 gap-[24px]">
              <div className={`col-span-12  relative after:bg-[var(--border-color)] dark:after:bg-[var(--border-dark)] sm:mx-0 md:mx-5`}>
                {/* <div className={`col-span-12 ${ads?.news_view_31 || ads?.news_view_32 ? "lg:col-span-8 xl:col-span-9" : "lg:col-span-12 xl:col-span-12"} relative after:bg-[var(--border-color)] dark:after:bg-[var(--border-dark)] sm:mx-0 md:mx-5`}> */}
                <div>
                  <div className="border-[#B42424] dark:border-[#B42424] border-b-[5px] mb-1 pb-1"></div>
                  <div className="flex items-center justify-between">
                    <h2 className="text-2xl py-4 font-bold">ವೆಬ್‌ ಸ್ಟೋರಿ</h2>
                    <div className="block">
                      <button className="text-[#B42424] bg-transparent border border-[#B42424] px-4 py-2 rounded-full hover:bg-[#B42424] hover:text-white transition duration-300">
                        View More <span className="text-lg">»</span>
                      </button>
                    </div>
                  </div>

                  {/* Scrollable Gallery Container */}
                  <div
                    // ref={galleryRef}
                    className="flex gap-6 overflow-x-auto pb-4 scrollbar-hide" // pb-4 for scrollbar space, scrollbar-hide to hide scrollbar
                  >
                    {posts?.map((item, postIndexs) => {
                      const { title, media } = item || {};
                      const mediaUrl = media?.[0]?.video_url || media?.[0]?.image_url;
                      const isVideo = media?.[0]?.video_url;

                      return (
                        <div
                          key={postIndexs}
                          className="flex-shrink-0 w-[200px] md:w-[200px] lg:w-[200px] xl:w-[200px] relative"
                        >
                          <div className="group flex flex-col">
                            <div className="overflow-hidden rounded-[12px] relative w-full h-[300px]">
                              {isVideo ? (
                                <div>
                                  <video
                                    ref={videoRef}
                                    className="w-full h-full object-cover duration-700 ease-out transform group-hover:scale-105"
                                    width={560}
                                    height={113}
                                    src={media?.[0]?.video_url}
                                    onLoadedMetadata={handleVideoLoad}
                                    title={title}
                                    autoPlay
                                    muted
                                    loop
                                  />
                                  <div
                                    className="absolute inset-0 bg-transparent cursor-pointer"
                                    onClick={() => handleOpenPopup(postIndexs)}
                                  ></div>
                                </div>
                              ) : (
                                <Image
                                  alt="Gallery Image"
                                  width={225}
                                  height={300}
                                  decoding="async"
                                  className="w-full h-full object-cover duration-700 ease-out transform group-hover:scale-105 cursor-pointer"
                                  onClick={() => handleOpenPopup(postIndexs)}
                                  src={media?.[0]?.image_url}
                                />
                              )}
                              <div className="absolute rounded-[5px] bottom-0 left-0 w-full h-1/2 bg-gradient-to-t from-black/100 via-black/20 text-white flex items-end px-3 py-5">
                                <h3 className="text-sm font-semibold line-clamp-2">
                                  {mediaUrl ? title : ""}
                                </h3>
                              </div>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>

              {/* Ads Section */}
              {/* {(ads?.news_view_31 || ads?.news_view_32) && (
                <div className="col-span-12 md:col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] dark:after:bg-[var(--border-dark)]">
                  <div className="w-full flex flex-row lg:flex-col lg:h-full lg:flex lg:items-center justify-center gap-4">
                    {ads?.news_view_31 && (
                      <div className="w-full flex items-center justify-center">
                        <div className="h-[250px]">
                          <AddCard imgPath={ads?.news_view_31} />
                        </div>
                      </div>
                    )}
                    {ads?.news_view_32 && (
                      <div className="w-full flex items-center justify-center hidden sm:flex lg:hidden">
                        <div className="h-[250px]">
                          <AddCard imgPath={ads?.news_view_32} />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )} */}

              {(adsSlot1 || adsSlot3) && (
                <div className="col-span-12 w-full lg:h-0 lg:opacity-0 lg:pointer-events-none lg:overflow-hidden">
                {/* <div className="col-span-12 md:col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] dark:after:bg-[var(--border-dark)]"> */}
                  <div className="w-full flex flex-row lg:flex-col lg:h-full lg:flex lg:items-center justify-center gap-4">
                    {adsSlot1 && (
                      <div className="bg-[#f9f9f9] w-full flex items-center justify-center">
                        <div className="h-[250px] min-w-[300px] w-full">
                          <AdsComponent adSlot={adsSlot1} style={{
                            display: "block",
                            width: "100%",
                            minHeight: "250px",
                            textAlign: "center",

                          }} />
                        </div>
                      </div>
                    )}
                    {adsSlot3 && (
                      <div className="bg-[#f9f9f9] w-full flex items-center justify-center hidden sm:flex ">
                        <div className="h-[250px] min-w-[300px] w-full">
                          <AdsComponent adSlot={adsSlot3} style={{
                            display: "block",
                            width: "100%",
                            minHeight: "250px",
                            textAlign: "center",

                          }} />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Popup Modal */}
          {isPopupOpen && (
            <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-80 z-50 overflow-y-auto py-10">
              <button
                onClick={handleClosePopup}
                className="absolute top-2 bg-black bg-opacity-50 text-white right-4 p-2 rounded-full text-3xl z-50"
              >
                <IoClose />
              </button>
              <button
                className="absolute top-2 right-16 bg-black bg-opacity-50 text-white p-2 rounded-full z-50"
                onClick={() => setIsPlaying(!isPlaying)}
              >
                {isPlaying ? <IoPause size={30} /> : <IoPlay size={30} />}
              </button>
              <div className="relative md:w-[60%] lg:w-[50%] xl:w-[45%] h-auto  max-w-4xl mx-4">


                <button
                  onClick={handlePrev}
                  className="absolute top-1/2 left-4 bg-black bg-opacity-50 text-white p-2 rounded-full text-3xl z-50"
                >
                  <IoChevronBack />
                </button>

                <button
                  onClick={handleNext}
                  className="absolute top-1/2 right-4 bg-black bg-opacity-50 text-white p-2 rounded-full text-3xl z-50"
                >
                  <IoChevronForward />
                </button>


                <div className="flex justify-center gap-1 mb-[20px]">
                  {posts[selectedPostIndex]?.media?.map((_, index) => (
                    <button
                      key={index}
                      className={`w-12 h-2 rounded-md transition-all duration-300 ${index === currentIndex
                        ? "bg-[#B42424]"
                        : "bg-gray-500 bg-opacity-50"
                        }`}
                      onClick={() => {
                        setCurrentIndex(index);
                        setIsPlaying(false);
                      }}
                      aria-label={`Go to slide ${index + 1}`}
                    />
                  ))}
                </div>
                <div className="flex  justify-center p-4 ">
                  {/* {photos?.map((photo, index) => ( */}
                  <div className=" relative w-[330px] h-[500px] xl:w-[470px] xl:h-[750px]">
                    {posts[selectedPostIndex]?.media?.[currentIndex]?.video_url ? (
                      <div className="relative ">
                        <video
                          key={`${selectedPostIndex}-${currentIndex}`}
                          ref={videoRef}
                          className="w-[330px] h-[500px] xl:w-[470px] xl:h-[750px] object-cover rounded-md"
                          width={560}
                          height={113}
                          src={posts[selectedPostIndex].media[currentIndex].video_url}
                          onLoadedMetadata={handleVideoLoad}
                          autoPlay
                          muted={isMuted}
                          controls={false}
                        />

                        {/* Video Controls Container */}
                        <div className="absolute top-4 left-0 right-0 flex justify-end gap-4">
                          {/* Play/Pause Button */}
                          <button
                            onClick={() => {
                              if (videoRef.current?.paused) {
                                videoRef.current?.play();
                                setIsPlaying(true);
                              } else {
                                videoRef.current?.pause();
                                setIsPlaying(false);
                              }
                            }}
                            className="bg-black/50 text-white p-2 rounded-full  transition"
                          >
                            {isPlaying ? <IoPause size={24} /> : <IoPlay size={24} />}
                          </button>

                          {/* Mute/Unmute Button */}
                          <button
                            onClick={() => setIsMuted(!isMuted)}
                            className="bg-black/70 text-white p-2 rounded-full hover:bg-black/90 transition"
                            aria-label={isMuted ? "Unmute" : "Mute"}
                          >
                            {isMuted ? <IoVolumeMute size={24} /> : <IoVolumeHigh size={24} />}
                          </button>
                          {/* Share Button */}
                          {/* <button
                            onClick={() => handleShare(posts[selectedPostIndex])}
                            className="bg-black/70 text-white p-2 rounded-full hover:bg-black/90 transition"
                            aria-label="Share"
                          >
                            <IoShareSocial size={24} />
                          </button> */}
                        </div>
                      </div>
                    ) : (
                      <Image
                        key={`${selectedPostIndex}-${currentIndex}`}
                        src={posts[selectedPostIndex]?.media?.[currentIndex]?.image_url || ''}
                        alt={`Image ${currentIndex + 1}`}
                        width={800}
                        height={500}
                        className="w-[330px] h-[500px] xl:w-[470px] xl:h-[750px] rounded-md object-cover"
                      />
                    )}

                    <div
                      className="absolute rounded-[5px] bottom-0 left-0 w-full h-1/2 max-h-[80vh] bg-gradient-to-t from-black/100 via-black/20 text-white flex items-end px-3 py-5"
                    >
                      <div
                        key={currentIndex}
                        className="animate-slide-up"
                      // initial={{ opacity: 0, y: 50 }} // Start position (hidden & lower)
                      // animate={{ opacity: 1, y: 0 }} // Final position (visible & normal)
                      // transition={{ duration: 2.5, ease: "easeOut" }} // Animation timing
                      >
                        <h1 className="text-lg font-semibold line-clamp-1">
                          {posts[selectedPostIndex]?.media?.[currentIndex]?.heading}
                        </h1>
                        <p className="text-sm mt-2 line-clamp-1">
                          {posts[selectedPostIndex]?.media?.[currentIndex]?.description}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>




              </div>
            </div>
          )}
        </section>
      )}
    </>
  );
};

export default PhotoGallery;