"use client"
import { useIntl } from "react-intl"

import SkeletonShimmer from "@scandic-hotels/design-system/SkeletonShimmer"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { AvailabilityEnum } from "@scandic-hotels/trpc/enums/selectHotel"

import { useSelectRateContext } from "../../../../../contexts/SelectRate/SelectRateContext"
import { ErrorBoundary } from "../../../../ErrorBoundary/ErrorBoundary"
import { RemoveBookingCodeButton } from "./RemoveBookingCodeButton/RemoveBookingCodeButton"
import { RoomPackageFilter } from "./RoomPackageFilter"

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

export function RoomsHeader({ roomIndex }: { roomIndex: number }) {
  return (
    // eslint-disable-next-line formatjs/no-literal-string-in-jsx
    <ErrorBoundary fallback={<div>Unable to render rooms header</div>}>
      <InnerRoomsHeader roomIndex={roomIndex} />
    </ErrorBoundary>
  )
}

function InnerRoomsHeader({ roomIndex }: { roomIndex: number }) {
  return (
    <div className={styles.container}>
      <AvailableRoomCount roomIndex={roomIndex} />
      <div className={styles.filters}>
        <RemoveBookingCodeButton />
        <RoomPackageFilter roomIndex={roomIndex} />
        {/* <BookingCodeFilter roomIndex={roomIndex} /> */}
      </div>
    </div>
  )
}

function AvailableRoomCount({ roomIndex }: { roomIndex: number }) {
  const intl = useIntl()
  const { isFetching, getAvailabilityForRoom } = useSelectRateContext()

  const roomAvailability = getAvailabilityForRoom(roomIndex) ?? []

  const availableRooms = roomAvailability.filter(
    (x) => x.status === AvailabilityEnum.Available
  ).length

  const totalRooms = roomAvailability.length

  const notAllRoomsAvailableText = intl.formatMessage(
    {
      defaultMessage:
        "{availableRooms}/{numberOfRooms, plural, one {# room type} other {# room types}} available",
    },
    {
      availableRooms,
      numberOfRooms: totalRooms,
    }
  )

  const allRoomsAvailableText = intl.formatMessage(
    {
      defaultMessage:
        "{numberOfRooms, plural, one {# room type} other {# room types}} available",
    },
    {
      numberOfRooms: totalRooms,
    }
  )

  if (isFetching) {
    return <SkeletonShimmer height="30px" width="25ch" />
  }

  return (
    <Typography variant="Title/Subtitle/md" className={styles.availableRooms}>
      <p>
        {availableRooms !== totalRooms
          ? notAllRoomsAvailableText
          : allRoomsAvailableText}
      </p>
    </Typography>
  )
}
