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

import {
  AncillaryStepEnum,
  createAddAncillaryStore,
} from "@/stores/my-stay/add-ancillary-flow"

import { getAncillarySessionData } from "@/components/HotelReservation/MyStay/utils/ancillaries"
import { AddAncillaryContext } from "@/contexts/AddAncillary"

import type { Ancillaries } from "@/types/components/myPages/myStay/ancillaries"
import type { AddAncillaryStore } from "@/types/contexts/add-ancillary"
import type { Room } from "@/types/stores/my-stay"

export function AddAncillaryProvider({
  ancillaries,
  booking,
  children,
}: {
  ancillaries: Ancillaries
  booking: Room
  children: React.ReactNode
}) {
  const storeRef = useRef<AddAncillaryStore>(undefined)
  if (!storeRef.current) {
    storeRef.current = createAddAncillaryStore(booking, ancillaries)
  }

  useEffect(() => {
    const savedData = getAncillarySessionData()
    if (savedData?.selectedAncillary) {
      storeRef.current?.setState({
        selectedAncillary: savedData.selectedAncillary,
        currentStep: AncillaryStepEnum.confirmation,
        isBreakfast: savedData.isBreakfast,
        isOpen: true,
      })
    }
  }, [])

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