"use client"
import { createContext, useContext } from "react"

import { useEnterDetailsStore } from "../../stores/enter-details"

import type { Room } from "@scandic-hotels/trpc/types/room"

import type { RoomState } from "../../stores/enter-details/types"

interface RoomContextValue {
  actions: RoomState["actions"]
  isComplete: RoomState["isComplete"]
  idx: number
  room: RoomState["room"]
  roomNr: number
  steps: RoomState["steps"]
}

const RoomContext = createContext<RoomContextValue | null>(null)

export function useRoomContext() {
  const ctx = useContext(RoomContext)
  if (!ctx) {
    throw new Error("Missing context value [RoomContext]")
  }
  return ctx
}

type RoomProviderProps = {
  idx: number
  room: Room
  children: React.ReactNode
}

export function RoomProvider({ children, idx }: RoomProviderProps) {
  const { actions, isComplete, room, steps } = useEnterDetailsStore(
    (state) => ({
      actions: state.rooms[idx].actions,
      isComplete: state.rooms[idx].isComplete,
      room: state.rooms[idx].room,
      steps: state.rooms[idx].steps,
    })
  )

  return (
    <RoomContext.Provider
      value={{
        actions,
        idx,
        isComplete,
        room,
        roomNr: idx + 1,
        steps,
      }}
    >
      {children}
    </RoomContext.Provider>
  )
}
