"use client"

import { LoadingSpinner } from "@scandic-hotels/design-system/LoadingSpinner"
import { trpc } from "@scandic-hotels/trpc/client"

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

import CarouselCard from "./CarouselCard"

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

import type {
  UpcomingStaysClientProps,
  UpcomingStaysNonNullResponseObject,
} from "@/types/components/myPages/stays/upcoming"

export default function UpcomingStaysCarousel({
  initialUpcomingStays,
}: UpcomingStaysClientProps) {
  const lang = useLang()
  const { data, isLoading } = trpc.user.stays.upcoming.useInfiniteQuery(
    {
      limit: 6,
      lang,
    },
    {
      getNextPageParam: (lastPage) => {
        return lastPage?.nextCursor
      },
      initialData: {
        pageParams: [undefined, 1],
        pages: [initialUpcomingStays],
      },
    }
  )

  if (isLoading) {
    return <LoadingSpinner />
  }

  const stays = data.pages
    .filter((page): page is UpcomingStaysNonNullResponseObject => !!page?.data)
    .flatMap((page) => page.data)

  if (!stays.length) {
    return null
  }

  return (
    <Carousel className={styles.carousel}>
      <Carousel.Content>
        {stays.map((stay) => (
          <Carousel.Item
            key={stay.attributes.confirmationNumber}
            className={styles.carouselItem}
          >
            <CarouselCard stay={stay} />
          </Carousel.Item>
        ))}
      </Carousel.Content>
      <Carousel.Previous className={styles.navigationButton} />
      <Carousel.Next className={styles.navigationButton} />
      <Carousel.Dots />
    </Carousel>
  )
}
