"use client"

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

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

import ToggleSidePeek from "@/components/HotelReservation/EnterDetails/SelectedRoom/ToggleSidePeek"
import FlexibilityOption from "@/components/HotelReservation/SelectRate/RoomSelection/FlexibilityOption"
import { ErrorCircleIcon } from "@/components/Icons"
import ImageGallery from "@/components/ImageGallery"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"

import { getIconForFeatureCode } from "../../utils"
import { cardVariants } from "./cardVariants"

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

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

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

  const rates = {
    saveRate: rateDefinitions.find(
      (rate) => rate.cancellationRule === "NotCancellable"
    ),
    changeRate: rateDefinitions.find(
      (rate) => rate.cancellationRule === "Changeable"
    ),
    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 petRoomPackage =
    (selectedPackages.includes(RoomPackageCodeEnum.PET_ROOM) &&
      packages?.find((pkg) => pkg.code === RoomPackageCodeEnum.PET_ROOM)) ||
    undefined

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

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

  const freeCancelation = intl.formatMessage({ id: "Free cancellation" })
  const nonRefundable = intl.formatMessage({ id: "Non-refundable" })
  const freeBooking = intl.formatMessage({ id: "Free rebooking" })
  const payLater = intl.formatMessage({ id: "Pay later" })
  const payNow = intl.formatMessage({ id: "Pay now" })

  const rateKey = useCallback(
    (key: string) => {
      switch (key) {
        case "flexRate":
          return freeCancelation
        case "saveRate":
          return nonRefundable
        default:
          return freeBooking
      }
    },
    [freeCancelation, freeBooking, nonRefundable]
  )

  const classNames = cardVariants({
    availability:
      roomConfiguration.status === "NotAvailable"
        ? "noAvailability"
        : "default",
  })

  return (
    <div className={classNames}>
      <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
                .filter((feature) => selectedPackages.includes(feature.code))
                .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. */}
            <ImageGallery
              images={images}
              title={roomConfiguration.roomType}
              fill
            />
          </div>
        )}
        <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>
          <div className={styles.toggleSidePeek}>
            {roomConfiguration.roomTypeCode && (
              <ToggleSidePeek
                hotelId={hotelId}
                roomTypeCode={roomConfiguration.roomTypeCode}
              />
            )}
          </div>
        </div>
        <div className={styles.roomDetails}>
          <Subtitle className={styles.name} type="two">
            {roomConfiguration.roomType}
          </Subtitle>
          {/* Out of scope for now        
            <Body>{descriptions?.short}</Body>
            */}
        </div>
      </div>
      <div className={styles.container}>
        <Caption color="uiTextHighContrast" type="bold">
          {intl.formatMessage({
            id: "Breakfast selection in next step.",
          })}
        </Caption>
        {roomConfiguration.status === "NotAvailable" ? (
          <div className={styles.noRoomsContainer}>
            <div className={styles.noRooms}>
              <ErrorCircleIcon color="red" width={16} />
              <Caption color="uiTextHighContrast" type="bold">
                {intl.formatMessage({
                  id: "This room is not available",
                })}
              </Caption>
            </div>
          </div>
        ) : (
          <div className={styles.flexibilityOptions}>
            {Object.entries(rates).map(([key, rate]) => (
              <FlexibilityOption
                key={key}
                name={rateKey(key)}
                value={key.toLowerCase()}
                paymentTerm={key === "flexRate" ? payLater : payNow}
                product={findProductForRate(rate)}
                priceInformation={getPriceInformationForRate(rate)}
                handleSelectRate={handleSelectRate}
                roomType={roomConfiguration.roomType}
                roomTypeCode={roomConfiguration.roomTypeCode}
                features={roomConfiguration.features}
                petRoomPackage={petRoomPackage}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
