"use client"
import { AnimatePresence, motion } from "framer-motion"
import { useEffect, useState } from "react"
import { Dialog, Modal, ModalOverlay } from "react-aria-components"

import FullView from "./FullView"
import Gallery from "./Gallery"

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

import type { LightboxProps } from "@/types/components/lightbox/lightbox"

export default function Lightbox({
  images,
  dialogTitle,
  onClose,
  isOpen,
}: LightboxProps) {
  const [selectedImageIndex, setSelectedImageIndex] = useState(0)
  const [isFullView, setIsFullView] = useState(false)

  useEffect(() => {
    if (isOpen) {
      setSelectedImageIndex(0)
      setIsFullView(false)
    }
  }, [isOpen])

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

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

  return (
    <ModalOverlay
      isOpen={isOpen}
      onOpenChange={onClose}
      className={styles.overlay}
      isDismissable
    >
      <Modal>
        <AnimatePresence>
          <Dialog aria-label={dialogTitle}>
            {isOpen && (
              <motion.div
                className={`${styles.content} ${
                  isFullView ? styles.fullViewContent : styles.galleryContent
                }`}
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1, x: "-50%", y: "-50%" }}
                exit={{ opacity: 0, scale: 0.95 }}
                transition={{ duration: 0.2 }}
              >
                {isFullView ? (
                  <FullView
                    image={images[selectedImageIndex]}
                    onClose={() => setIsFullView(false)}
                    onNext={handleNext}
                    onPrev={handlePrev}
                    currentIndex={selectedImageIndex}
                    totalImages={images.length}
                  />
                ) : (
                  <Gallery
                    images={images}
                    onClose={onClose}
                    onSelectImage={(image) => {
                      setSelectedImageIndex(
                        images.findIndex((img) => img === image)
                      )
                    }}
                    onImageClick={() => setIsFullView(true)}
                    selectedImage={images[selectedImageIndex]}
                  />
                )}
              </motion.div>
            )}
          </Dialog>
        </AnimatePresence>
      </Modal>
    </ModalOverlay>
  )
}
