"use client"

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

import Image from "@/components/Image"
import Lightbox from "@/components/Lightbox"
import Button from "@/components/TempDesignSystem/Button"
import { mapImageVaultImagesToGalleryImages } from "@/utils/imageGallery"

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

import type { ImageVaultAsset } from "@/types/components/imageVault"

interface TopImageProps {
  images: ImageVaultAsset[]
  destinationName: string
}

export default function TopImages({ images, destinationName }: TopImageProps) {
  const intl = useIntl()
  const [lightboxState, setLightboxState] = useState({
    open: false,
    activeIndex: 0,
  })
  const lightboxImages = mapImageVaultImagesToGalleryImages(images)
  const maxWidth = 1366 // 1366px is the max width of the image container
  const visibleImages = images.slice(0, 3)

  return (
    <div className={styles.topImages}>
      <div className={styles.imageWrapper}>
        {visibleImages.map((image, index) => {
          const width = index === 0 ? maxWidth : maxWidth / visibleImages.length
          const height =
            image.dimensions.aspectRatio >= 1
              ? Math.ceil(width / image.dimensions.aspectRatio)
              : Math.ceil(width * image.dimensions.aspectRatio)

          return (
            <Image
              key={image.url}
              src={image.url}
              alt={image.meta.alt || image.meta.caption || ""}
              width={width}
              height={height}
              focalPoint={image.focalPoint}
              className={`${styles.image} ${images.length > 1 ? styles.clickable : ""}`}
              onClick={() =>
                images.length
                  ? setLightboxState({ open: true, activeIndex: index })
                  : null
              }
              priority
            />
          )
        })}
      </div>
      {images.length > 1 && (
        <>
          <Button
            theme="base"
            intent="inverted"
            size="small"
            onClick={() => setLightboxState({ open: true, activeIndex: 0 })}
            className={styles.seeAllButton}
          >
            {intl.formatMessage({
              defaultMessage: "See all photos",
            })}
          </Button>
          {lightboxState.open ? (
            <Lightbox
              images={lightboxImages}
              dialogTitle={intl.formatMessage(
                {
                  defaultMessage: "{title} - Image gallery",
                },
                { title: destinationName }
              )}
              activeIndex={lightboxState.activeIndex}
              onClose={() => setLightboxState({ open: false, activeIndex: 0 })}
            />
          ) : null}
        </>
      )}
    </div>
  )
}
