"use client"

import { TRPCClientError } from "@trpc/client"
import { useIntl } from "react-intl"

import { AlertTypeEnum } from "@scandic-hotels/trpc/types/alert"

import Alert from "@/components/TempDesignSystem/Alert"
import { useSelectRateContext } from "@/contexts/SelectRate/SelectRateContext"

import { RateSummary } from "./RateSummary"
import Rooms from "./Rooms"
import { RoomsContainerSkeleton } from "./RoomsContainerSkeleton"

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

import type { AppRouter } from "@scandic-hotels/trpc/routers/appRouter"

import type { RoomsContainerProps } from "@/types/components/hotelReservation/selectRate/roomsContainer"

export function RoomsContainer({}: RoomsContainerProps) {
  const intl = useIntl()

  const {
    availability: { error, isFetching, isError },
    input: { hasError: hasInputError },
  } = useSelectRateContext()

  if (isFetching) {
    return <RoomsContainerSkeleton />
  }

  if (isError || hasInputError) {
    const errorMessage = getErrorMessage(error, intl)

    return (
      <div className={styles.errorContainer}>
        <Alert type={AlertTypeEnum.Alarm} heading={errorMessage} />
      </div>
    )
  }

  return (
    <>
      <Rooms />
      <RateSummary />
    </>
  )
}

function getErrorMessage(error: unknown, intl: ReturnType<typeof useIntl>) {
  if (!isTRPCClientError(error)) {
    return intl.formatMessage({
      defaultMessage: "Something went wrong",
    })
  }

  const firstError = error.data?.zodError?.formErrors?.at(0)

  switch (firstError) {
    case "FROMDATE_INVALID":
    case "TODATE_INVALID":
    case "TODATE_MUST_BE_AFTER_FROMDATE":
    case "FROMDATE_CANNOT_BE_IN_THE_PAST": {
      return intl.formatMessage({
        defaultMessage: "Invalid dates",
      })
    }
    default:
      return intl.formatMessage({
        defaultMessage: "Something went wrong",
      })
  }
}

function isTRPCClientError(
  cause: unknown
): cause is TRPCClientError<AppRouter> {
  return cause instanceof TRPCClientError
}
