import { createContext, useContext, useState } from 'react'
import type { ModuleStatus } from '../data/modulesData'

const DEFAULT_STATUSES: Record<string, ModuleStatus> = {
  'housekeeping':     'active',
  'channel-manager':  'active',
  'wifi-auth':        'active',
  'payments':         'active',
  'tv-welcome':       'active',
  'smart-locks':      'active',
  'olap-reports':     'active',
  'website-builder':  'active',
  'booking-widget':   'active',
  'pos':              'active',
  'reviews':          'active',
  'room-service':     'active',
  'rental':           'active',
  'migration':        'active',
}

interface ModulesContextValue {
  statuses: Record<string, ModuleStatus>
  setStatus: (id: string, status: ModuleStatus) => void
  isActive: (id: string) => boolean
}

const ModulesContext = createContext<ModulesContextValue | null>(null)

const MODULES_VERSION = '2'

export function ModulesProvider({ children }: { children: React.ReactNode }) {
  const [statuses, setStatuses] = useState<Record<string, ModuleStatus>>(() => {
    try {
      // Reset stored statuses when version changes so new defaults apply
      const storedVersion = localStorage.getItem('hotelsync-modules-ver')
      if (storedVersion !== MODULES_VERSION) {
        localStorage.removeItem('hotelsync-modules')
        localStorage.setItem('hotelsync-modules-ver', MODULES_VERSION)
        return DEFAULT_STATUSES
      }
      const stored = localStorage.getItem('hotelsync-modules')
      return stored ? { ...DEFAULT_STATUSES, ...JSON.parse(stored) } : DEFAULT_STATUSES
    } catch {
      return DEFAULT_STATUSES
    }
  })

  const setStatus = (id: string, status: ModuleStatus) => {
    setStatuses(prev => {
      const next = { ...prev, [id]: status }
      localStorage.setItem('hotelsync-modules', JSON.stringify(next))
      return next
    })
  }

  const isActive = (id: string) => statuses[id] === 'active' || statuses[id] === 'trial'

  return (
    <ModulesContext.Provider value={{ statuses, setStatus, isActive }}>
      {children}
    </ModulesContext.Provider>
  )
}

export function useModules() {
  const ctx = useContext(ModulesContext)
  if (!ctx) throw new Error('useModules must be used within ModulesProvider')
  return ctx
}
