"use client"
import * as Dialog from "@radix-ui/react-dialog"
import { AnimatePresence, motion } from "framer-motion"
import Image from "next/image"
import React, { useState } from "react"

import { ChevronRightIcon } from "@/components/Icons"
import ArrowRightIcon from "@/components/Icons/ArrowRight"
import CloseIcon from "@/components/Icons/Close"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"

import styles from "./desktopLightbox.module.css"

import {
  DesktopLightboxProps,
  FullViewProps,
  GalleryProps,
} from "@/types/components/lightbox/desktopLightbox"

export function DesktopLightbox({ images, children }: DesktopLightboxProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [selectedImageIndex, setSelectedImageIndex] = useState(0)
  const [isFullView, setIsFullView] = useState(false)

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      setTimeout(() => {
        setIsOpen(false)
        setSelectedImageIndex(0)
        setIsFullView(false)
      }, 300) // 300ms delay
    } else {
      setIsOpen(true)
    }
  }

  const handleNext = () => {
    setSelectedImageIndex((prevIndex) => (prevIndex + 1) % images.length)
  }

  const handlePrev = () => {
    setSelectedImageIndex(
      (prevIndex) => (prevIndex - 1 + images.length) % images.length
    )
  }

  const triggerElement = React.Children.map(
    children,
    function mapChild(child): React.ReactNode {
      if (React.isValidElement(child)) {
        if (child.props.id === "lightboxTrigger") {
          return React.cloneElement(child, {
            onClick: () => setIsOpen(true),
          } as React.HTMLAttributes<HTMLElement>)
        } else if (child.props.children) {
          return React.cloneElement(child, {
            children: React.Children.map(child.props.children, mapChild),
          } as React.HTMLAttributes<HTMLElement>)
        }
      }
      return child
    }
  )

  return (
    <>
      {triggerElement}
      <Dialog.Root open={isOpen} onOpenChange={handleOpenChange}>
        <AnimatePresence>
          {isOpen && (
            <Dialog.Portal forceMount>
              <Dialog.Overlay asChild>
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className={styles.overlay}
                />
              </Dialog.Overlay>
              <Dialog.Content className={styles.content}>
                <motion.div
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  style={{
                    width: "100%",
                    height: "100%",
                  }}
                >
                  {isFullView ? (
                    <FullView
                      image={images[selectedImageIndex]}
                      onClose={() => setIsFullView(false)}
                      onNext={handleNext}
                      onPrev={handlePrev}
                      currentIndex={selectedImageIndex}
                      totalImages={images.length}
                    />
                  ) : (
                    <Gallery
                      images={images}
                      onClose={() => setIsOpen(false)}
                      onSelectImage={(image) => {
                        setSelectedImageIndex(
                          images.findIndex((img) => img.url === image.url)
                        )
                      }}
                      onImageClick={() => setIsFullView(true)}
                      selectedImage={images[selectedImageIndex]}
                    />
                  )}
                </motion.div>
              </Dialog.Content>
            </Dialog.Portal>
          )}
        </AnimatePresence>
      </Dialog.Root>
    </>
  )
}

function Gallery({
  images,
  onClose,
  onSelectImage,
  onImageClick,
  selectedImage,
}: GalleryProps) {
  const mainImage = selectedImage || images[0]
  const mainImageIndex = images.findIndex((img) => img.url === mainImage.url)

  function getThumbImages() {
    const thumbs = []
    for (let i = 1; i <= 5; i++) {
      const index = (mainImageIndex + i) % images.length
      thumbs.push(images[index])
    }
    return thumbs
  }

  return (
    <div className={styles.galleryContainer}>
      <Button
        intent="text"
        size="small"
        theme="base"
        className={styles.closeButton}
        onClick={onClose}
      >
        <CloseIcon width={32} height={32} />
      </Button>
      <div className={styles.galleryHeader}>
        <div className={styles.imageCaption}>
          <Caption color="textMediumContrast">{mainImage.alt}</Caption>
        </div>
      </div>
      <div className={styles.mainImageContainer}>
        <Image
          src={mainImage.url}
          alt={mainImage.alt}
          layout="fill"
          objectFit="cover"
          onClick={onImageClick}
        />
      </div>
      <div className={styles.thumbnailGrid}>
        {getThumbImages().map((image, index) => (
          <motion.div
            key={index}
            className={styles.thumbnailContainer}
            onClick={() => onSelectImage(image)}
          >
            <Image
              src={image.url}
              alt={image.alt}
              layout="fill"
              objectFit="cover"
            />
          </motion.div>
        ))}
      </div>
    </div>
  )
}

function FullView({
  image,
  onClose,
  onNext,
  onPrev,
  currentIndex,
  totalImages,
}: FullViewProps) {
  return (
    <div className={styles.fullViewContainer}>
      <Button
        intent="text"
        size="small"
        className={styles.backButton}
        onClick={onClose}
      >
        <ChevronRightIcon
          color="white"
          width={32}
          height={32}
          className={styles.leftTransformIcon}
        />
      </Button>
      <div className={styles.fullViewHeader}>
        <span className={styles.imagePosition}>
          <Caption color="white">
            {`${currentIndex + 1} / ${totalImages}`}
          </Caption>
        </span>
      </div>
      <div className={styles.fullViewImageContainer}>
        <AnimatePresence initial={false} custom={currentIndex}>
          <motion.div
            key={image.url}
            custom={currentIndex}
            initial={{ opacity: 0, x: 300 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -300 }}
            transition={{ duration: 0.3 }}
            className={styles.fullViewImage}
          >
            <Image
              src={image.url}
              alt={image.alt}
              layout="fill"
              objectFit="contain"
            />
          </motion.div>
        </AnimatePresence>
        <motion.button
          className={`${styles.navigationButton} ${styles.prevButton}`}
          onClick={onPrev}
        >
          <ArrowRightIcon
            color="burgundy"
            className={styles.leftTransformIcon}
          />
        </motion.button>
        <motion.button
          className={`${styles.navigationButton} ${styles.nextButton}`}
          onClick={onNext}
        >
          <ArrowRightIcon color="burgundy" />
        </motion.button>
      </div>
      <div className={styles.fullViewFooter}>
        <Body color="white">{image.alt}</Body>
      </div>
    </div>
  )
}
