"use client"

import { trpc } from "@/lib/trpc/client"

import LoadingSpinner from "@/components/LoadingSpinner"
import Grids from "@/components/TempDesignSystem/Grids"
import useLang from "@/hooks/useLang"

import ListContainer from "../ListContainer"
import ShowMoreButton from "../ShowMoreButton"
import StayCard from "../StayCard"

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

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

  if (isLoading) {
    return <LoadingSpinner />
  }

  function loadMoreData() {
    if (hasNextPage) {
      fetchNextPage()
    }
  }

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

  return stays.length ? (
    <ListContainer>
      <Grids.Stackable>
        {stays.map((stay) => (
          <StayCard key={stay.attributes.confirmationNumber} stay={stay} />
        ))}
      </Grids.Stackable>
      {hasNextPage ? (
        <ShowMoreButton disabled={isFetching} loadMoreData={loadMoreData} />
      ) : null}
    </ListContainer>
  ) : null
}
