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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

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

import Image from "@/components/Image"
import Button from "@/components/TempDesignSystem/Button"
import Chip from "@/components/TempDesignSystem/Chip"
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/SelectRate/Room"
import { isValidClientSession } from "@/utils/clientSession"

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

import { CurrencyEnum } from "@/types/enums/currency"
import { RateEnum } from "@/types/enums/rate"

export default function SelectedRoomPanel() {
  const intl = useIntl()
  const { dates, roomCategories, rooms } = useRatesStore((state) => ({
    dates: {
      from: state.booking.fromDate,
      to: state.booking.toDate,
    },
    roomCategories: state.roomCategories,
    rooms: state.rooms,
  }))
  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)
  const {
    actions: { modifyRate },
    isMainRoom,
    roomNr,
    selectedPackages,
    selectedRate,
  } = useRoomContext()
  const nights = dt(dates.to).diff(dt(dates.from), "days")

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

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

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

  if (!selectedRate) {
    return null
  }

  const selectedPackagesCurrency = selectedPackages.find(
    (pkg) => pkg.localPrice.currency
  )
  const selectedPackagesPrice = selectedPackages.reduce(
    (total, pkg) => total + pkg.localPrice.totalPrice,
    0
  )
  const selectedPackagesPricePerNight = selectedPackagesPrice / nights

  const night = intl.formatMessage({
    defaultMessage: "night",
  })
  let selectedProduct
  if (
    isUserLoggedIn &&
    isMainRoom &&
    "member" in selectedRate.product &&
    selectedRate.product.member
  ) {
    const { localPrice } = selectedRate.product.member
    selectedProduct = `${localPrice.pricePerNight + selectedPackagesPricePerNight} ${localPrice.currency} / ${night}`
  } else if ("public" in selectedRate.product && selectedRate.product.public) {
    const { localPrice } = selectedRate.product.public
    selectedProduct = `${localPrice.pricePerNight + selectedPackagesPricePerNight} ${localPrice.currency} / ${night}`
  } else if ("corporateCheque" in selectedRate.product) {
    const { localPrice } = selectedRate.product.corporateCheque
    selectedProduct = `${localPrice.numberOfCheques} ${CurrencyEnum.CC}`
    if (
      (localPrice.additionalPricePerStay || selectedPackagesPrice) &&
      localPrice.currency
    ) {
      selectedProduct = `${selectedProduct} + ${localPrice.additionalPricePerStay + selectedPackagesPrice} ${localPrice.currency}`
    }
  } else if ("voucher" in selectedRate.product) {
    selectedProduct = `${selectedRate.product.voucher.numberOfVouchers} ${CurrencyEnum.Voucher}`
    if (selectedPackagesPrice && selectedPackagesCurrency) {
      selectedProduct = `${selectedProduct} + ${selectedPackagesPrice} ${selectedPackagesCurrency}`
    }
  }

  if (!selectedProduct) {
    console.error("Selected product is unknown")
    return null
  }

  const showModifyButton =
    isMainRoom ||
    (!isMainRoom && rooms.slice(0, roomNr).every((room) => room.selectedRate))

  return (
    <div className={styles.selectedRoomPanel}>
      <div className={styles.content}>
        <Caption color="uiTextHighContrast">
          {intl.formatMessage(
            {
              defaultMessage: "Room {roomIndex}",
            },
            { roomIndex: roomNr }
          )}
        </Caption>
        <Subtitle className={styles.subtitle} color="uiTextHighContrast">
          {selectedRate.roomType}
        </Subtitle>
        <Body color="uiTextMediumContrast">
          {getRateTitle(selectedRate.product.rate)}
        </Body>
        <Body color="uiTextHighContrast">{selectedProduct}</Body>
      </div>
      <div className={styles.imageContainer}>
        {images?.[0]?.imageSizes?.tiny ? (
          <Image
            alt={selectedRate.roomType ?? images[0].metaData?.altText ?? ""}
            className={styles.img}
            height={300}
            src={images[0].imageSizes.tiny}
            width={600}
          />
        ) : null}
        {showModifyButton && (
          <div className={styles.modifyButtonContainer}>
            <Button clean onClick={modifyRate}>
              <Chip size="small" variant="uiTextHighContrast">
                <MaterialIcon icon="edit_square" />
                {intl.formatMessage({
                  defaultMessage: "Change",
                })}
              </Chip>
            </Button>
          </div>
        )}
      </div>
    </div>
  )
}
