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

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

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

import type { Ancillaries } from "@/types/components/myPages/myStay/ancillaries"
import type { AddAncillaryStore } from "@/types/contexts/add-ancillary"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"

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

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

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