"use client";

import {
  Carousel,
  CarouselContent,
  CarouselItem,
} from "@/components/ui/carousel";
import Autoplay from "embla-carousel-autoplay";
import { useLocale } from "next-intl";
import { useState } from "react";
import "react-image-gallery/styles/css/image-gallery.css";
import "../../../globals.css";
import placeHolder from "/public/products/Placeholder.png";
import FallbackImage from "../FallbackImage";

function convertToEmbed(url) {
  // Regular expression to match a YouTube watch URL
  const pattern =
    /https?:\/\/(?:www\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/;

  // Replace the URL with the embed format
  const embedUrl = url.replace(pattern, "https://www.youtube.com/embed/$1");

  return embedUrl;
}

export default function ImagesRedesign({ images, videoUrl }) {
  const [isVideo, setIsVideo] = useState(false);
  const locale = useLocale();
  const dir = locale === "en" ? "ltr" : "rtl";

  const [selectedImg, setSelectedImg] = useState(
    images?.[0]?.photo || placeHolder
  );

  const showOnGallery = [...images, { videoUrl }];
  const setImg = (element) => {
    setIsVideo(false);
    if (element?.videoLink) {
      setIsVideo(true);
      return;
    }
    setSelectedImg(element);
  };

  return (
    <section className="flex-1 overflow-hidden">
      {isVideo ? (
        <div className="relative h-[500px] w-full">
          <iframe
            width={"100%"}
            height={"100%"}
            className="absolute inset-0"
            src={convertToEmbed(videoUrl)}
            title="YouTube video player"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            referrerPolicy="strict-origin-when-cross-origin"
            allowFullScreen
          ></iframe>
        </div>
      ) : (
        <div className="h-[500px] w-full flex items-center justify-center border-[1px]  rounded-lg">
          <FallbackImage
            width={400}
            height={400}
            alt="An image for the product"
            src={selectedImg}
            className="rounded-xl object-contain max-h-full max-w-full"
          />
        </div>
      )}
      <Carousel
        dir={dir}
        className="mt-10 mx-auto max-w-full"
        plugins={[
          Autoplay({
            delay: 1000,
            stopOnMouseEnter: true,
          }),
        ]}
        opts={{
          align: "start",
          loop: true,
          direction: locale === "en" ? "ltr" : "rtl",
        }}
      >
        <CarouselContent dir={dir} className="-ml-1 max-w-full p-2">
          {showOnGallery.map((media, i) => {
            if (media.videoUrl) {
              return (
                <CarouselItem
                  dir={dir}
                  key={media.videoUrl}
                  className="basis-1/2 md:basis-1/3 lg:basis-1/4 pl-1"
                >
                  <div
                    className="relative h-[130px] md:h-32 max-w-[230px] w-full"
                    onMouseOver={() => setImg({ videoLink: media.videoUrl })}
                  >
                    <iframe
                      className="absolute inset-0 w-full h-full"
                      src={convertToEmbed(media.videoUrl)}
                      title="YouTube video player"
                      frameBorder="0"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                      referrerPolicy="strict-origin-when-cross-origin"
                      allowFullScreen
                    ></iframe>
                  </div>
                </CarouselItem>
              );
            }
            return (
              <CarouselItem
                dir={dir}
                key={media.photo}
                className="basis-1/2 md:basis-1/3 lg:basis-1/4 pl-1"
              >
                <div
                  className="relative h-[130px] md:h-32 lg:w-[90%] cursor-pointer border-[1px] rounded-md  hover:border-black"
                  onMouseOver={() => setImg(media.photo)}
                >
                  <FallbackImage
                    alt="product"
                    src={media.photo}
                    className="object-contain rounded-xl p-5"
                    fill
                  />
                </div>
              </CarouselItem>
            );
          })}
        </CarouselContent>
      </Carousel>
    </section>
  );
}
