"use client"
import { usePathname, useSearchParams } from "next/navigation"
import { useRef } from "react"
import { useIntl } from "react-intl"

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

import { RatesContext } from "@/contexts/Rates"

import type { RatesStore } from "@/types/contexts/rates"
import type { RatesProviderProps } from "@/types/providers/rates"

export default function RatesProvider({
  booking,
  children,
  hotelType,
  isUserLoggedIn,
  roomCategories,
  roomsAvailability,
  vat,
}: RatesProviderProps) {
  const storeRef = useRef<RatesStore>()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const intl = useIntl()

  if (!storeRef.current) {
    storeRef.current = createRatesStore({
      booking,
      hotelType,
      isUserLoggedIn,
      labels: {
        accessibilityRoom: intl.formatMessage({ id: "Accessibility room" }),
        allergyRoom: intl.formatMessage({ id: "Allergy-friendly room" }),
        petRoom: intl.formatMessage({ id: "Pet room" }),
      },
      pathname,
      roomCategories,
      roomsAvailability,
      searchParams: new URLSearchParams(searchParams),
      vat,
    })
  }

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