"use client"

import { useState } from "react"
import { useIntl } from "react-intl"

import { GalleryIcon } from "@/components/Icons"
import Image from "@/components/Image"
import Lightbox from "@/components/Lightbox"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"

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

import type { ImageGalleryProps } from "@/types/components/imageGallery"

export default function ImageGallery({
  images,
  title,
  fill,
  height = 280,
}: ImageGalleryProps) {
  const intl = useIntl()
  const [lightboxIsOpen, setLightboxIsOpen] = useState(false)
  const [imageError, setImageError] = useState(false)
  const imageProps = fill ? { fill } : { height, width: height * 1.5 }

  if (!images || images.length === 0 || imageError) {
    return <div className={styles.imagePlaceholder} />
  }

  return (
    <>
      <div
        className={styles.triggerArea}
        role="button"
        onClick={() => setLightboxIsOpen(true)}
        aria-label={intl.formatMessage({ id: "Open image gallery" })}
      >
        <Image
          className={styles.image}
          src={images[0].imageSizes.medium}
          alt={images[0].metaData.altText}
          onError={() => setImageError(true)}
          {...imageProps}
        />
        <div className={styles.imageCount}>
          <GalleryIcon color="white" />
          <Footnote color="white" type="label">
            {images.length}
          </Footnote>
        </div>
      </div>
      <Lightbox
        images={images}
        dialogTitle={title}
        isOpen={lightboxIsOpen}
        onClose={() => setLightboxIsOpen(false)}
      />
    </>
  )
}
