import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react'

export interface BedTypeItem {
  value: string     // unique key stored in DB (e.g. 'double', 'sofa')
  label: string     // display name
  icon: string      // emoji
  capacity: number  // max guests on this bed type
}

const DEFAULT_BED_TYPES: BedTypeItem[] = [
  { value: 'single', label: 'Кровать 1-сп.',  icon: '🛏', capacity: 1 },
  { value: 'double', label: 'Кровать 2-сп.',  icon: '🛏', capacity: 2 },
  { value: 'queen',  label: 'Queen-кровать',   icon: '🛏', capacity: 2 },
  { value: 'king',   label: 'King-кровать',    icon: '🛏', capacity: 2 },
  { value: 'twin',   label: 'Две кровати',     icon: '🛏', capacity: 2 },
  { value: 'sofa',   label: 'Диван',           icon: '🛋', capacity: 1 },
  { value: 'bunk',   label: 'Двухъярусная',    icon: '🛏', capacity: 2 },
  { value: 'cot',    label: 'Раскладушка',     icon: '🪑', capacity: 1 },
]

interface BedTypesContextValue {
  bedTypes: BedTypeItem[]
  addBedType: (item: BedTypeItem) => void
  removeBedType: (value: string) => void
  updateBedType: (value: string, patch: Partial<Omit<BedTypeItem, 'value'>>) => void
}

const BedTypesContext = createContext<BedTypesContextValue | null>(null)

export function BedTypesProvider({ children }: { children: ReactNode }) {
  const [bedTypes, setBedTypes] = useState<BedTypeItem[]>(DEFAULT_BED_TYPES)

  const addBedType = (item: BedTypeItem) =>
    setBedTypes(prev => prev.find(b => b.value === item.value) ? prev : [...prev, item])

  const removeBedType = (value: string) =>
    setBedTypes(prev => prev.filter(b => b.value !== value))

  const updateBedType = (value: string, patch: Partial<Omit<BedTypeItem, 'value'>>) =>
    setBedTypes(prev => prev.map(b => b.value === value ? { ...b, ...patch } : b))

  return (
    <BedTypesContext.Provider value={{ bedTypes, addBedType, removeBedType, updateBedType }}>
      {children}
    </BedTypesContext.Provider>
  )
}

export function useBedTypes() {
  const ctx = useContext(BedTypesContext)
  if (!ctx) throw new Error('useBedTypes must be used within BedTypesProvider')
  return ctx
}
