"use client"
import { useEffect } from "react"

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

import { RoomContext } from "@/contexts/SelectRate/Room"
import useLang from "@/hooks/useLang"

import { BookingCodeFilterEnum } from "@/types/enums/bookingCodeFilter"
import { RateTypeEnum } from "@/types/enums/rateType"
import type { RoomProviderProps } from "@/types/providers/select-rate/room"

export default function RoomProvider({
  children,
  idx,
  room,
}: RoomProviderProps) {
  const lang = useLang()
  const { activeRoom, booking, roomAvailability, selectedFilter } =
    useRatesStore((state) => ({
      activeRoom: state.activeRoom,
      booking: state.booking,
      roomAvailability: state.roomsAvailability?.[idx],
      selectedFilter: state.rooms[idx].selectedFilter,
    }))
  const { appendRegularRates, ...actions } = room.actions
  const roomNr = idx + 1

  const hasRedemptionRates = room.rooms.some((room) => room.redemptions.length)
  const hasCorporateChequeOrVoucherRates = room.rooms.some((room) =>
    room.code.some((product) => {
      if ("corporateCheque" in product) {
        return product.corporateCheque.rateType === RateTypeEnum.CorporateCheque
      } else if ("voucher" in product) {
        return product.voucher.rateType === RateTypeEnum.Voucher
      }
      return false
    })
  )

  const dontShowRegularRates =
    hasRedemptionRates || hasCorporateChequeOrVoucherRates

  // Extra query needed to fetch regular rates upon user
  // selecting to view all rates.
  // TODO: Setup route to handle singular availability call
  const { data, isFetched, isFetching } =
    trpc.hotel.availability.roomsCombinedAvailability.useQuery(
      {
        adultsCount: [room.bookingRoom.adults],
        childArray: room.bookingRoom.childrenInRoom
          ? [room.bookingRoom.childrenInRoom]
          : undefined,
        hotelId: booking.hotelId,
        lang,
        roomStayEndDate: booking.toDate,
        roomStayStartDate: booking.fromDate,
      },
      {
        enabled: !!(
          booking.bookingCode &&
          selectedFilter === BookingCodeFilterEnum.All &&
          !dontShowRegularRates
        ),
      }
    )

  useEffect(() => {
    if (isFetched && !isFetching && data?.length) {
      const regularRates = data[0]
      if ("roomConfigurations" in regularRates) {
        appendRegularRates(regularRates.roomConfigurations)
      }
    }
  }, [appendRegularRates, data, isFetched, isFetching])

  return (
    <RoomContext.Provider
      value={{
        ...room,
        actions,
        isActiveRoom: activeRoom === idx,
        isFetchingAdditionalRate: isFetched ? false : isFetching,
        isMainRoom: roomNr === 1,
        roomAvailability,
        roomNr,
        totalRooms: room.rooms.length,
      }}
    >
      {children}
    </RoomContext.Provider>
  )
}
