"use client"

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

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

import ListContainer from "../ListContainer"
import OldStayCard from "../OldStayCard"
import ShowMoreButton from "../ShowMoreButton"

import type {
  PreviousStaysClientProps,
  PreviousStaysNonNullResponseObject,
} from "@/types/components/myPages/stays/previous"

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

  if (isLoading) {
    return <LoadingSpinner />
  }

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

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

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