"use client"
import { useSession } from "next-auth/react"
import { useIntl } from "react-intl"

import { useRatesStore } from "@/stores/select-rate"

import { getRates } from "@/components/HotelReservation/SelectRate/utils"
import { EditIcon } from "@/components/Icons"
import Image from "@/components/Image"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import { useRoomContext } from "@/contexts/Room"
import { isValidClientSession } from "@/utils/clientSession"

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

import type { Room as SelectedRateRoom } from "@/types/components/hotelReservation/selectRate/selectRate"

interface SelectedRoomPanelProps {
  room: SelectedRateRoom
}

export default function SelectedRoomPanel({ room }: SelectedRoomPanelProps) {
  const intl = useIntl()
  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)
  const { rateDefinitions, roomCategories } = useRatesStore((state) => ({
    rateDefinitions: state.roomsAvailability?.rateDefinitions,
    roomCategories: state.roomCategories,
  }))
  const {
    actions: { modifyRate },
    roomNr,
    selectedRate,
  } = useRoomContext()

  const images = roomCategories.find((roomCategory) =>
    roomCategory.roomTypes.some(
      (roomType) => roomType.code === selectedRate?.roomTypeCode
    )
  )?.images

  if (!rateDefinitions) {
    return null
  }

  const rates = getRates(rateDefinitions)

  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" })

  function getRateDetails(rateCode: string) {
    const rate = Object.keys(rates).find((k) =>
      rates[k as keyof typeof rates].find((a) => a.rateCode === rateCode)
    )

    switch (rate) {
      case "change":
        return `${freeBooking}, ${payNow}`
      case "flex":
        return `${freeCancelation}, ${payLater}`
      case "save":
      default:
        return `${nonRefundable}, ${payNow}`
    }
  }

  const rateCode =
    isUserLoggedIn && selectedRate?.product.productType.member
      ? selectedRate?.product.productType.member?.rateCode
      : selectedRate?.product.productType.public.rateCode

  return (
    <div className={styles.selectedRoomPanel}>
      <div>
        <Caption color="uiTextHighContrast">
          {intl.formatMessage(
            { id: "Room {roomIndex}" },
            { roomIndex: roomNr }
          )}
        </Caption>
        <Subtitle className={styles.subtitle} color="uiTextHighContrast">
          {selectedRate?.roomType}
        </Subtitle>
        <Body color="uiTextMediumContrast">
          {rateCode ? getRateDetails(rateCode) : null}
        </Body>
        <Body color="uiTextHighContrast">
          {selectedRate?.product.productType.public.localPrice.pricePerNight}{" "}
          {selectedRate?.product.productType.public.localPrice.currency}/
          {intl.formatMessage({ id: "night" })}
        </Body>
      </div>
      <div className={styles.imageAndModifyButtonContainer}>
        {images?.[0]?.imageSizes?.tiny && (
          <div className={styles.imageContainer}>
            <Image
              alt={selectedRate?.roomType ?? images[0].metaData?.altText ?? ""}
              fill
              src={images[0].imageSizes.tiny}
            />
          </div>
        )}
        <div className={styles.modifyButtonContainer}>
          <Button variant="icon" size="small" onClick={modifyRate}>
            <EditIcon />
            {intl.formatMessage({ id: "Modify" })}
          </Button>
        </div>
      </div>
    </div>
  )
}
