"use client"

import { useState } from "react"
import { Button as ButtonRAC } from "react-aria-components"
import { useIntl } from "react-intl"

import { Button } from "@scandic-hotels/design-system/Button"

import Image from "@/components/Image"
import Lightbox from "@/components/Lightbox/"
import { mapApiImagesToGalleryImages } from "@/utils/imageGallery"

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

import type { PreviewImagesProps } from "@/types/components/hotelPage/previewImages"

export default function PreviewImages({
  images,
  hotelName,
}: PreviewImagesProps) {
  const intl = useIntl()
  const [lightboxState, setLightboxState] = useState({
    activeIndex: 0,
    isOpen: false,
  })

  const lightboxImages = mapApiImagesToGalleryImages(images)

  return (
    <div className={styles.imageWrapper}>
      {lightboxImages.slice(0, 3).map((image, index) => (
        <ButtonRAC
          key={image.src}
          className={styles.imageButton}
          aria-label={intl.formatMessage({
            defaultMessage: "See all photos",
          })}
          onPress={() =>
            setLightboxState({
              activeIndex: index,
              isOpen: true,
            })
          }
        >
          <Image
            src={image.src}
            alt={image.alt}
            title={image.caption || ""}
            width={index === 0 ? 752 : 292}
            height={index === 0 ? 540 : 266}
            className={styles.image}
          />
        </ButtonRAC>
      ))}
      {images.length > 1 && (
        <>
          <Button
            variant="Primary"
            color="Inverted"
            size="Small"
            onPress={() =>
              setLightboxState({
                activeIndex: 0,
                isOpen: true,
              })
            }
            typography="Body/Supporting text (caption)/smBold"
            className={styles.seeAllButton}
          >
            {intl.formatMessage({
              defaultMessage: "See all photos",
            })}
          </Button>
          {lightboxState.isOpen ? (
            <Lightbox
              images={lightboxImages}
              dialogTitle={intl.formatMessage(
                {
                  defaultMessage: "{title} - Image gallery",
                },
                { title: hotelName }
              )}
              activeIndex={lightboxState.activeIndex}
              onClose={() =>
                setLightboxState({ activeIndex: 0, isOpen: false })
              }
            />
          ) : null}
        </>
      )}
    </div>
  )
}
