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

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

import { DetailsContext } from "@/contexts/Details"

import type { DetailsStore } from "@/types/contexts/enter-details"
import type { DetailsProviderProps } from "@/types/providers/enter-details"
import type { InitialState } from "@/types/stores/enter-details"

export default function EnterDetailsProvider({
  bedTypes,
  booking,
  breakfastPackages,
  children,
  packages,
  roomRate,
  searchParamsStr,
  step,
  user,
}: DetailsProviderProps) {
  const storeRef = useRef<DetailsStore>()

  if (!storeRef.current) {
    const initialData: InitialState = { booking, packages, roomRate }
    if (bedTypes.length === 1) {
      initialData.bedType = {
        description: bedTypes[0].description,
        roomTypeCode: bedTypes[0].value,
      }
    }
    if (!breakfastPackages?.length) {
      initialData.breakfast = false
    }

    storeRef.current = createDetailsStore(
      initialData,
      step,
      searchParamsStr,
      user
    )
  }

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