"use client";

import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
import Autoplay from "embla-carousel-autoplay";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import "react-image-gallery/styles/css/image-gallery.css";
import "../../globals.css";
import FallbackImage from "../shared/FallbackImage";
import placeHolder from "/public/products/Placeholder.png";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";

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 Images({ images, videoUrl }) {
  const [isVideo, setIsVideo] = useState(false);
  const locale = useLocale();
  const dir = locale === "en" ? "ltr" : "rtl";
  const t = useTranslations();
  const [selectedImg, setSelectedImg] = useState(
    images?.[0]?.photo || placeHolder
  );

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

  return (
    <section className="flex-1 overflow-hidden">
      <div className="rounded-xl border shadow-md p-4 bg-gray-100 max-w-4xl mx-auto">
        {isVideo ? (
          <div className="relative h-[500px] w-full overflow-hidden rounded-lg">
            <iframe
              width="100%"
              height="100%"
              className="absolute inset-0 rounded-lg"
              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>
        ) : (
          <Dialog>
            <DialogTrigger asChild>
              <div className="h-[500px] w-full flex items-center justify-center overflow-hidden rounded-lg cursor-pointer">
                <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>
            </DialogTrigger>
            <DialogContent
              // dialogOverlayStyle={
              //   "lg:!fixed lg:!end-10 lg:!top-0 lg:!w-1/2 lg:!h-full lg:!translate-x-0 lg:!translate-y-0 "
              // }
              className="lg:!fixed lg:!end-10 lg:!top-0 lg:!w-1/2 lg:!h-full lg:!translate-x-0 lg:!translate-y-0 !border-none !rounded-none bg-transparent"
            >
              <Carousel
                dir={dir}
                className="mt-10 mx-auto max-w-full  w-full "
                plugins={[
                  Autoplay({
                    delay: 1000,
                    stopOnMouseEnter: true,
                  }),
                ]}
                opts={{
                  align: "center",
                  loop: true,
                  direction: locale === "en" ? "ltr" : "rtl",
                }}
              >
                <CarouselContent
                  dir={dir}
                  className="-ml-1 max-w-full p-2 bg-transparent  "
                >
                  {showOnGallery.map((media) => {
                    if (media.videoUrl) {
                      return (
                        <CarouselItem
                          dir={dir}
                          key={media.videoUrl}
                          className="w-full h-full"
                        >
                          <div
                            className="relative h-full 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
                        key={media.photo}
                        dir={dir}
                        className="pl-1 w-full h-full bg-transparent"
                      >
                        <h3 className="font-medium text-sm text-gray-500 text-center">
                          {t("zoomInAndOut")}
                        </h3>
                        <div
                          className="relative h-full w-full cursor-pointer shadow-md flex justify-center items-center"
                          onMouseOver={() => setImg(media.photo)}
                        >
                          <TransformWrapper
                            initialScale={1}
                            minScale={0.5}
                            maxScale={10}
                            centerOnInit={true}
                            wheel={{ step: 0.3 }}
                            className="w-full h-full"
                          >
                            <TransformComponent className="w-full h-full flex items-center justify-center">
                              <div
                                className="relative cursor-zoom-in
          w-full h-full max-w-[80vh] max-h-[80vh]
          sm:w-[70vh] sm:h-[70vh]
          md:w-[75vh] md:h-[75vh]
          lg:w-[80vh] lg:h-[80vh]
          max-sm:w-[90vw] max-sm:h-[60vh]
          max-sm:max-w-[90vw] max-sm:max-h-[60vh]
        "
                              >
                                <FallbackImage
                                  alt="product"
                                  src={media.photo}
                                  className="object-contain rounded-xl"
                                  fill
                                />
                              </div>
                            </TransformComponent>
                          </TransformWrapper>
                        </div>
                      </CarouselItem>
                    );
                  })}
                </CarouselContent>
                <CarouselPrevious className="bg-secondary  text-main !size-12 hover:bg-secondary  translate-x-16  transition-all transform  duration-500 ease-in-out   border-none hover:text-main hidden lg:flex opacity-0 group-hover:opacity-100" />
                <CarouselNext className="bg-secondary text-main !size-12 hover:bg-secondary -translate-x-16  transition-all transform  duration-500 ease-in-out   border-none hover:text-main hidden lg:flex opacity-0 group-hover:opacity-100" />
              </Carousel>
            </DialogContent>
          </Dialog>
        )}
      </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) => {
            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 w-full cursor-pointer shadow-md"
                  onMouseOver={() => setImg(media.photo)}
                >
                  <FallbackImage
                    alt="product"
                    src={media.photo}
                    className="object-contain rounded-xl"
                    fill
                  />
                </div>
              </CarouselItem>
            );
          })}
        </CarouselContent>
      </Carousel>
    </section>
  );
}
