"use client"

import { createElement } from "react"
import { useIntl } from "react-intl"

import { RateDefinition } from "@/server/routers/hotels/output"

import FlexibilityOption from "@/components/HotelReservation/SelectRate/RoomSelection/FlexibilityOption"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"

import RoomSidePeek from "../../../../SidePeeks/RoomSidePeek"
import ImageGallery from "../../ImageGallery"
import { getIconForFeatureCode } from "../../utils"

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

import type { RoomCardProps } from "@/types/components/hotelReservation/selectRate/roomCard"

export default function RoomCard({
  rateDefinitions,
  roomConfiguration,
  roomCategories,
  handleSelectRate,
}: RoomCardProps) {
  const intl = useIntl()

  const rates = {
    saveRate: rateDefinitions.find(
      (rate) => rate.cancellationRule === "NonCancellable"
    ),
    changeRate: rateDefinitions.find(
      (rate) => rate.cancellationRule === "Modifiable"
    ),
    flexRate: rateDefinitions.find(
      (rate) => rate.cancellationRule === "CancellableBefore6PM"
    ),
  }

  function findProductForRate(rate: RateDefinition | undefined) {
    return rate
      ? roomConfiguration.products.find(
          (product) =>
            product.productType.public?.rateCode === rate.rateCode ||
            product.productType.member?.rateCode === rate.rateCode
        )
      : undefined
  }

  function getPriceInformationForRate(rate: RateDefinition | undefined) {
    return rateDefinitions.find((def) => def.rateCode === rate?.rateCode)
      ?.generalTerms
  }

  const selectedRoom = roomCategories.find(
    (room) => room.name === roomConfiguration.roomType
  )

  const { roomSize, occupancy, descriptions, images } = selectedRoom || {}
  const mainImage = images?.[0]

  return (
    <div className={styles.card}>
      <div className={styles.cardBody}>
        <div className={styles.specification}>
          <Caption color="uiTextMediumContrast" className={styles.guests}>
            {intl.formatMessage(
              {
                id: "booking.guests",
              },
              { nrOfGuests: occupancy?.total }
            )}
          </Caption>
          <Caption color="uiTextMediumContrast">
            {roomSize?.min === roomSize?.max
              ? roomSize?.min
              : `${roomSize?.min}-${roomSize?.max}`}
            m²
          </Caption>
          {selectedRoom && (
            <RoomSidePeek room={selectedRoom} buttonSize="small" />
          )}
        </div>
        <div className={styles.container}>
          <div className={styles.roomDetails}>
            <Subtitle className={styles.name} type="two">
              {roomConfiguration.roomType}
            </Subtitle>
            <Body>{descriptions?.short}</Body>
          </div>
          <Caption color="uiTextHighContrast">
            {intl.formatMessage({
              id: "Breakfast selection in next step.",
            })}
          </Caption>
          <div className={styles.flexibilityOptions}>
            {Object.entries(rates).map(([key, rate]) => (
              <FlexibilityOption
                key={key}
                name={intl.formatMessage({
                  id:
                    key === "flexRate"
                      ? "Free cancellation"
                      : key === "saveRate"
                        ? "Non-refundable"
                        : "Free rebooking",
                })}
                value={key.toLowerCase()}
                paymentTerm={intl.formatMessage({
                  id: key === "flexRate" ? "Pay later" : "Pay now",
                })}
                product={findProductForRate(rate)}
                priceInformation={getPriceInformationForRate(rate)}
                handleSelectRate={handleSelectRate}
                roomType={roomConfiguration.roomType}
                roomTypeCode={roomConfiguration.roomTypeCode}
                features={roomConfiguration.features}
              />
            ))}
          </div>
        </div>
      </div>
      {mainImage && (
        <div className={styles.imageContainer}>
          <div className={styles.chipContainer}>
            {roomConfiguration.roomsLeft < 5 && (
              <span className={styles.chip}>
                <Footnote
                  color="burgundy"
                  textTransform="uppercase"
                >{`${roomConfiguration.roomsLeft} ${intl.formatMessage({ id: "Left" })}`}</Footnote>
              </span>
            )}
            {roomConfiguration.features.map((feature) => (
              <span className={styles.chip} key={feature.code}>
                {createElement(getIconForFeatureCode(feature.code), {
                  width: 16,
                  height: 16,
                  color: "burgundy",
                })}
              </span>
            ))}
          </div>
          {/*NOTE: images from the test API are hosted on test3.scandichotels.com,
         which can't be accessed unless on Scandic's Wifi or using Citrix. */}
          {images && (
            <ImageGallery images={images} title={roomConfiguration.roomType} />
          )}
        </div>
      )}
    </div>
  )
}
