"use client"

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

import useLang from "@/hooks/useLang"

import ListContainer from "../ListContainer"
import ShowMoreButton from "../ShowMoreButton"
import { Card } from "./Card"

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

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

export function Cards({ 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>
      <div className={styles.grid}>
        {stays.map((stay) => (
          <Card key={stay.attributes.confirmationNumber} stay={stay} />
        ))}
      </div>
      {hasNextPage ? (
        <ShowMoreButton disabled={isFetching} loadMoreData={loadMoreData} />
      ) : null}
    </ListContainer>
  )
}
