"use client"

import { useIntl } from "react-intl"

import CodeRateCard from "@scandic-hotels/design-system/CodeRateCard"

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

import {
  sumPackages,
  sumPackagesRequestedPrice,
} from "@/components/HotelReservation/utils"
import { useRoomContext } from "@/contexts/SelectRate/Room"
import useRateTitles from "@/hooks/booking/useRateTitles"

import {
  isSelectedCorporateCheque,
  isSelectedPriceProduct,
  isSelectedVoucher,
} from "./isSelected"
import { calculatePricePerNightPriceProduct } from "./totalPricePerNight"

import type { SharedRateCardProps } from "@/types/components/hotelReservation/selectRate/rates"
import type { CodeProduct } from "@/types/trpc/routers/hotel/roomAvailability"

interface CodeProps extends SharedRateCardProps {
  code: CodeProduct[]
}

export default function Code({
  code,
  handleSelectRate,
  nights,
  roomTypeCode,
}: CodeProps) {
  const intl = useIntl()
  const { roomNr, selectedPackages, selectedRate } = useRoomContext()
  const bookingCode = useRatesStore((state) => state.booking.bookingCode)
  const rateTitles = useRateTitles()
  const night = intl
    .formatMessage({
      defaultMessage: "night",
    })
    .toUpperCase()

  return code.map((product) => {
    let bannerText = ""
    if (product.rateDefinition.breakfastIncluded) {
      bannerText = `${bookingCode} ∙ ${intl.formatMessage({
        defaultMessage: "Breakfast included",
      })}`
    } else {
      bannerText = `${bookingCode} ∙ ${intl.formatMessage({
        defaultMessage: "Breakfast excluded",
      })}`
    }
    const rateTermDetails = product.rateDefinitionMember
      ? [
          {
            title: product.rateDefinition.title,
            terms: product.rateDefinition.generalTerms,
          },
          {
            title: product.rateDefinitionMember.title,
            terms: product.rateDefinitionMember.generalTerms,
          },
        ]
      : [
          {
            title: product.rateDefinition.title,
            terms: product.rateDefinition.generalTerms,
          },
        ]

    const pkgsSum = sumPackages(selectedPackages)
    const pkgsSumRequested = sumPackagesRequestedPrice(selectedPackages)

    if ("corporateCheque" in product) {
      const { localPrice, rateCode, requestedPrice } = product.corporateCheque
      let price = `${localPrice.numberOfCheques} CC`
      if (localPrice.additionalPricePerStay) {
        price = `${price} + ${localPrice.additionalPricePerStay + pkgsSum.price}`
      } else if (pkgsSum.price) {
        price = `${price} + ${pkgsSum.price}`
      }

      const isSelected = isSelectedCorporateCheque(
        product,
        selectedRate,
        roomTypeCode
      )

      const currency =
        localPrice.additionalPricePerStay > 0 || pkgsSum.price > 0
          ? (localPrice.currency ?? pkgsSum.currency ?? "")
          : ""

      const approximateRate =
        requestedPrice?.additionalPricePerStay && requestedPrice?.currency
          ? {
              label: intl.formatMessage({
                defaultMessage: "Approx.",
              }),
              price:
                `${requestedPrice.numberOfCheques} CC + ` +
                requestedPrice.additionalPricePerStay,
              unit: requestedPrice.currency,
            }
          : undefined

      return (
        <CodeRateCard
          key={product.rate}
          approximateRate={approximateRate}
          bannerText={bannerText}
          handleChange={() => handleSelectRate(product)}
          isSelected={isSelected}
          name={`rateCode-${roomNr}-${rateCode}`}
          paymentTerm={rateTitles[product.rate].paymentTerm}
          rate={{
            label: product.rateDefinition?.title,
            price,
            unit: currency,
          }}
          rateTitle={rateTitles[product.rate].title}
          rateTermDetails={rateTermDetails}
          value={rateCode}
        />
      )
    }

    if ("voucher" in product) {
      const { numberOfVouchers, rateCode } = product.voucher
      const isSelected = isSelectedVoucher(product, selectedRate, roomTypeCode)

      const voucherMsg = intl
        .formatMessage({
          defaultMessage: "Voucher",
        })
        .toUpperCase()
      let price = `${numberOfVouchers} ${voucherMsg}`
      if (pkgsSum.price) {
        price = `${price} + ${pkgsSum.price}`
      }
      return (
        <CodeRateCard
          key={product.rate}
          bannerText={bannerText}
          handleChange={() => handleSelectRate(product)}
          isSelected={isSelected}
          name={`rateCode-${roomNr}-${rateCode}`}
          paymentTerm={rateTitles[product.rate].paymentTerm}
          rate={{
            label: product.rateDefinition?.title,
            price,
            unit: pkgsSum.currency ?? "",
          }}
          rateTitle={rateTitles[product.rate].title}
          rateTermDetails={rateTermDetails}
          value={rateCode}
        />
      )
    }

    if (product.public) {
      const { localPrice, rateCode, requestedPrice } = product.public
      const pricePerNight = calculatePricePerNightPriceProduct(
        localPrice.pricePerNight,
        requestedPrice?.pricePerNight,
        nights,
        pkgsSum.price,
        pkgsSumRequested.price
      )

      const approximateRate =
        pricePerNight.totalRequestedPrice && requestedPrice?.currency
          ? {
              label: intl.formatMessage({
                defaultMessage: "Approx.",
              }),
              price: pricePerNight.totalRequestedPrice,
              unit: requestedPrice.currency,
            }
          : undefined

      const regularPricePerNight = calculatePricePerNightPriceProduct(
        localPrice.regularPricePerNight,
        requestedPrice?.regularPricePerNight,
        nights,
        pkgsSum.price,
        pkgsSumRequested.price
      )

      const comparisonRate =
        +regularPricePerNight.totalPrice > +pricePerNight.totalPrice
          ? {
              price: regularPricePerNight.totalPrice,
              unit: localPrice.currency,
            }
          : undefined

      const isSelected = isSelectedPriceProduct(
        product,
        selectedRate,
        roomTypeCode
      )

      return (
        <CodeRateCard
          key={product.rate}
          approximateRate={approximateRate}
          bannerText={bannerText}
          comparisonRate={comparisonRate}
          handleChange={() => handleSelectRate(product)}
          isSelected={isSelected}
          name={`rateCode-${roomNr}-${rateCode}`}
          paymentTerm={rateTitles[product.rate].paymentTerm}
          rate={{
            label: product.rateDefinition?.title,
            price: pricePerNight.totalPrice,
            unit: `${localPrice.currency}/${night}`,
          }}
          rateTitle={rateTitles[product.rate].title}
          rateTermDetails={rateTermDetails}
          value={rateCode}
        />
      )
    }

    return null
  })
}
