import { useContext } from "react"
import { create, useStore } from "zustand"

import { BookingConfirmationContext } from "@/contexts/BookingConfirmation"

import type {
  BookingConfirmationState,
  InitialState,
} from "@/types/stores/booking-confirmation"

export function createBookingConfirmationStore(initialState: InitialState) {
  return create<BookingConfirmationState>()((set) => ({
    rooms: initialState.rooms,
    bookingCode: initialState.bookingCode,
    currencyCode: initialState.currencyCode,
    fromDate: initialState.fromDate,
    toDate: initialState.toDate,
    roomCategories: initialState.roomCategories,
    vat: initialState.vat,
    formattedTotalCost: initialState.formattedTotalCost,
    isVatCurrency: initialState.isVatCurrency,
    totalBookingPrice: initialState.totalBookingPrice,
    totalBookingCheques: initialState.totalBookingCheques,
    actions: {
      setRoom: (room, idx) => {
        set((state) => {
          const rooms = [...state.rooms]
          rooms[idx] = room

          const totalBookingPrice = rooms.reduce((acc, room) => {
            return acc + (room?.totalPrice ?? 0)
          }, 0)
          const totalBookingCheques = rooms.reduce((acc, room) => {
            return acc + (room?.cheques ?? 0)
          }, 0)
          return { rooms, totalBookingPrice, totalBookingCheques }
        })
      },
      setFormattedTotalCost: (formattedTotalCost) => {
        set(() => ({ formattedTotalCost }))
      },
    },
  }))
}

export function useBookingConfirmationStore<T>(
  selector: (store: BookingConfirmationState) => T
) {
  const store = useContext(BookingConfirmationContext)

  if (!store) {
    throw new Error(
      "useBookingConfirmationStore must be used within BookingConfirmationProvider"
    )
  }

  return useStore(store, selector)
}
