"use client"

import { cx } from "class-variance-authority"
import { useCallback } from "react"

import { useDestinationPageHotelsMapStore } from "@/stores/destination-page-hotels-map"

import { Carousel } from "@/components/Carousel"

import HotelMapCard from "../HotelMapCard"

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

import type { DestinationPagesHotelData } from "@/types/hotel"

interface MapCardCarouselProps {
  visibleHotels: DestinationPagesHotelData[]
}
export default function HotelCardCarousel({
  visibleHotels,
}: MapCardCarouselProps) {
  const { activeMarker, setActiveMarker } = useDestinationPageHotelsMapStore()

  const selectedHotelIdx = visibleHotels.findIndex(
    ({ hotel }) => hotel.id === activeMarker
  )

  const handleScrollSelect = useCallback(
    (idx: number) => {
      if (selectedHotelIdx !== -1) {
        setActiveMarker(visibleHotels[idx]?.hotel.id)
      }
    },
    [setActiveMarker, visibleHotels, selectedHotelIdx]
  )

  return (
    <Carousel
      className={styles.carousel}
      scrollToIdx={selectedHotelIdx}
      align="center"
      opts={{ containScroll: false }}
      onScrollSelect={handleScrollSelect}
    >
      <Carousel.Content className={styles.carouselContent}>
        {visibleHotels.map(({ hotel, url }) => (
          <Carousel.Item key={hotel.id} className={styles.item}>
            <HotelMapCard
              className={cx(styles.carouselCard, {
                [styles.noActiveHotel]: !activeMarker,
              })}
              tripadvisorRating={hotel.tripadvisor}
              hotelName={hotel.name}
              url={url}
              image={getImage({ hotel, url })}
              amenities={hotel.detailedFacilities.slice(0, 3)}
            />
          </Carousel.Item>
        ))}
      </Carousel.Content>
    </Carousel>
  )
}

function getImage(hotel: DestinationPagesHotelData) {
  return {
    src: hotel.hotel.galleryImages?.[0]?.imageSizes.medium,
    alt:
      hotel.hotel.galleryImages?.[0]?.metaData.altText ||
      hotel.hotel.galleryImages?.[0]?.metaData.altText_En,
  }
}
