"use client"
import { useSearchParams } from "next/navigation"
import { useRef } from "react"

import { createDetailsStore } from "@/stores/details"

import { getQueryParamsForEnterDetails } from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { DetailsContext } from "@/contexts/Details"

import type { DetailsStore } from "@/types/contexts/details"
import type { DetailsProviderProps } from "@/types/providers/details"

export default function DetailsProvider({
  children,
  isMember,
}: DetailsProviderProps) {
  const storeRef = useRef<DetailsStore>()
  const searchParams = useSearchParams()

  if (!storeRef.current) {
    const booking = getQueryParamsForEnterDetails(searchParams)
    storeRef.current = createDetailsStore({ booking }, isMember)
  }

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