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

import NoRateAvailableCard from "@scandic-hotels/design-system/NoRateAvailableCard"
import RegularRateCard from "@scandic-hotels/design-system/RegularRateCard"

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

import { isSelectedPriceProduct } from "./isSelected"
import { calculatePricePerNightPriceProduct } from "./totalPricePerNight"

import type { SharedRateCardProps } from "@/types/components/hotelReservation/selectRate/rates"
import { BookingCodeFilterEnum } from "@/types/enums/bookingCodeFilter"
import type { PriceProduct } from "@/types/trpc/routers/hotel/roomAvailability"

interface Rate {
  label: string
  price: string
  unit: string
}

interface Rates {
  memberRate?: Rate
  rate?: Rate
}

interface RegularProps extends SharedRateCardProps {
  regular: PriceProduct[]
}

export default function Regular({
  handleSelectRate,
  nights,
  regular,
  roomTypeCode,
}: RegularProps) {
  const intl = useIntl()
  const rateTitles = useRateTitles()
  const { isMainRoom, roomNr, selectedFilter, selectedPackages, selectedRate } =
    useRoomContext()
  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)

  if (selectedFilter === BookingCodeFilterEnum.Discounted) {
    return null
  }

  const night = intl
    .formatMessage({
      defaultMessage: "night",
    })
    .toUpperCase()
  const pkgsSum = sumPackages(selectedPackages)
  const pkgsSumRequested = sumPackagesRequestedPrice(selectedPackages)

  const standardPriceMsg = intl.formatMessage({
    defaultMessage: "Standard price",
  })

  const memberPriceMsg = intl.formatMessage({
    defaultMessage: "Member price",
  })

  const approxMsg = intl.formatMessage({
    defaultMessage: "Approx.",
  })

  return regular.map((product) => {
    const { member, public: standard } = product
    const isMainRoomAndLoggedIn = isMainRoom && isUserLoggedIn
    const isMainRoomLoggedInWithoutMember =
      isMainRoomAndLoggedIn && !product.member
    const noRateAvailable = !product.member && !product.public
    const hideStandardPrice = isMainRoomAndLoggedIn && !!member
    const isNotLoggedInAndOnlyMemberRate = !isUserLoggedIn && !standard
    const rateCode = hideStandardPrice ? member.rateCode : standard?.rateCode
    if (
      noRateAvailable ||
      isMainRoomLoggedInWithoutMember ||
      !rateCode ||
      isNotLoggedInAndOnlyMemberRate
    ) {
      return (
        <NoRateAvailableCard
          key={product.rate}
          noPricesAvailableText={rateTitles.noPriceAvailable}
          paymentTerm={rateTitles[product.rate].paymentTerm}
          rateTitle={rateTitles[product.rate].title}
          variant="Regular"
        />
      )
    }

    const memberPricePerNight = member
      ? calculatePricePerNightPriceProduct(
          member.localPrice.pricePerNight,
          member.requestedPrice?.pricePerNight,
          nights,
          pkgsSum.price,
          pkgsSumRequested.price
        )
      : undefined
    const standardPricePerNight = standard
      ? calculatePricePerNightPriceProduct(
          standard.localPrice.pricePerNight,
          standard.requestedPrice?.pricePerNight,
          nights,
          pkgsSum.price,
          pkgsSumRequested.price
        )
      : undefined

    let approximateMemberRatePrice = null
    const rates: Rates = {}
    if (memberPricePerNight) {
      rates.memberRate = {
        label: memberPriceMsg,
        price: memberPricePerNight.totalPrice,
        unit: `${member!.localPrice.currency}/${night}`,
      }

      if (memberPricePerNight.totalRequestedPrice) {
        approximateMemberRatePrice = memberPricePerNight.totalRequestedPrice
      }
    }

    let approximateStandardRatePrice = null
    if (standardPricePerNight) {
      rates.rate = {
        label: standardPriceMsg,
        price: standardPricePerNight.totalPrice,
        unit: `${standard!.localPrice.currency}/${night}`,
      }

      if (standardPricePerNight.totalRequestedPrice && !isUserLoggedIn) {
        approximateStandardRatePrice = standardPricePerNight.totalRequestedPrice
      }
    }

    let approximatePrice = ""
    if (approximateStandardRatePrice && approximateMemberRatePrice) {
      approximatePrice = `${approximateStandardRatePrice}/${approximateMemberRatePrice}`
    } else if (approximateStandardRatePrice) {
      approximatePrice = approximateStandardRatePrice
    } else if (approximateMemberRatePrice) {
      approximatePrice = approximateMemberRatePrice
    }

    const requestedCurrency =
      standard?.requestedPrice?.currency || member?.requestedPrice?.currency
    const approximateRate =
      approximatePrice && requestedCurrency
        ? {
            label: approxMsg,
            price: approximatePrice,
            unit: requestedCurrency,
          }
        : undefined

    const isSelected = isSelectedPriceProduct(
      product,
      selectedRate,
      roomTypeCode
    )

    const rateTermDetails = product.rateDefinitionMember
      ? [
          {
            title: standardPriceMsg,
            terms: product.rateDefinition.generalTerms,
          },
          {
            title: memberPriceMsg,
            terms: product.rateDefinitionMember.generalTerms,
          },
        ]
      : [
          {
            title: standardPriceMsg,
            terms: product.rateDefinition.generalTerms,
          },
        ]

    return (
      <RegularRateCard
        {...rates}
        key={product.rate}
        approximateRate={approximateRate}
        handleChange={() => handleSelectRate(product)}
        hidePublicRate={hideStandardPrice}
        isSelected={isSelected}
        name={`rateCode-${roomNr}-${rateCode}`}
        paymentTerm={rateTitles[product.rate].paymentTerm}
        rateTitle={rateTitles[product.rate].title}
        value={rateCode}
        rateTermDetails={rateTermDetails}
      />
    )
  })
}
