"use client"

import { useSession } from "next-auth/react"

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

import SkeletonShimmer from "@/components/SkeletonShimmer"
import Divider from "@/components/TempDesignSystem/Divider"
import { useRoomContext } from "@/contexts/SelectRate/Room"
import { isValidClientSession } from "@/utils/clientSession"

import BreakfastMessage from "./BreakfastMessage"
import Campaign from "./Campaign"
import Code from "./Code"
import Redemptions from "./Redemptions"
import Regular from "./Regular"

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

export default function Rates({
  roomConfiguration: {
    breakfastIncludedInAllRates,
    breakfastIncludedInAllRatesMember,
    campaign,
    code,
    features,
    redemptions,
    regular,
    roomType,
    roomTypeCode,
  },
}: RatesProps) {
  const {
    actions: { selectRate },
    isFetchingAdditionalRate,
    selectedFilter,
  } = useRoomContext()
  const nights = useRatesStore((state) =>
    dt(state.booking.toDate).diff(state.booking.fromDate, "days")
  )
  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)
  function handleSelectRate(product: Product) {
    selectRate({ features, product, roomType, roomTypeCode }, isUserLoggedIn)
  }

  const sharedProps = {
    handleSelectRate,
    nights,
    roomTypeCode,
  }
  const showAllRates = selectedFilter === BookingCodeFilterEnum.All
  const hasBookingCodeRates = !!(campaign.length || code.length)
  const hasRegularRates = !!regular.length
  const showDivider = showAllRates && hasBookingCodeRates && hasRegularRates

  return (
    <>
      <Code {...sharedProps} code={code} />
      <Campaign {...sharedProps} campaign={campaign} />
      <Redemptions {...sharedProps} redemptions={redemptions} />
      {showDivider ? <Divider color="borderDividerSubtle" /> : null}
      {isFetchingAdditionalRate ? (
        <>
          <SkeletonShimmer height="100px" />
          <SkeletonShimmer height="100px" />
        </>
      ) : null}
      <BreakfastMessage
        breakfastIncludedMember={breakfastIncludedInAllRatesMember}
        breakfastIncludedStandard={breakfastIncludedInAllRates}
        hasRegularRates={!!regular.length}
      />
      <Regular {...sharedProps} regular={regular} />
    </>
  )
}
