"use client"

import { useRef } from "react"
import { useIntl } from "react-intl"

import { createBookingConfirmationStore } from "@/stores/booking-confirmation"

import { BookingConfirmationContext } from "@/contexts/BookingConfirmation"
import { formatPrice } from "@/utils/numberFormatting"

import type { BookingConfirmationStore } from "@/types/contexts/booking-confirmation"
import { CurrencyEnum } from "@/types/enums/currency"
import type { BookingConfirmationProviderProps } from "@/types/providers/booking-confirmation"

export default function BookingConfirmationProvider({
  bookingCode,
  children,
  currencyCode,
  fromDate,
  toDate,
  rooms,
  vat,
}: BookingConfirmationProviderProps) {
  const intl = useIntl()
  const storeRef = useRef<BookingConfirmationStore>()

  if (!storeRef.current) {
    const totalBookingPrice = rooms.reduce((acc, room) => {
      const reservationTotalPrice = room?.totalPrice || 0
      return acc + reservationTotalPrice
    }, 0)
    let formattedTotalCost = formatPrice(intl, totalBookingPrice, currencyCode)
    const totalBookingPoints = rooms.reduce((acc, room) => {
      return acc + (room?.roomPoints ?? 0)
    }, 0)
    let isVatCurrency = true
    if (totalBookingPoints) {
      isVatCurrency = false
      formattedTotalCost = formatPrice(
        intl,
        totalBookingPoints,
        CurrencyEnum.POINTS,
        totalBookingPrice,
        currencyCode
      )
    }
    const initialData = {
      bookingCode,
      currencyCode,
      fromDate,
      toDate,
      rooms,
      vat,
      isVatCurrency,
      formattedTotalCost,
      totalBookingPrice,
    }

    storeRef.current = createBookingConfirmationStore(initialData)
  }

  return (
    <BookingConfirmationContext.Provider value={storeRef.current}>
      {children}
    </BookingConfirmationContext.Provider>
  )
}
