import { createContext, useContext, useEffect, useState } from 'react'

export type ThemeMode = 'light' | 'dark' | 'auto'
type Theme = 'light' | 'dark'

interface ThemeContextValue {
  mode: ThemeMode
  theme: Theme
  setMode: (mode: ThemeMode) => void
  toggle: () => void
}

const ThemeContext = createContext<ThemeContextValue | null>(null)

function getSystemTheme(): Theme {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setModeState] = useState<ThemeMode>(() => {
    return (localStorage.getItem('hotelsync-theme') as ThemeMode | null) ?? 'light'
  })

  const [theme, setTheme] = useState<Theme>(() => {
    const stored = localStorage.getItem('hotelsync-theme') as ThemeMode | null
    if (!stored || stored === 'light') return 'light'
    if (stored === 'dark') return 'dark'
    return getSystemTheme()
  })

  useEffect(() => {
    if (mode === 'auto') {
      setTheme(getSystemTheme())
      const mq = window.matchMedia('(prefers-color-scheme: dark)')
      const handler = (e: MediaQueryListEvent) => setTheme(e.matches ? 'dark' : 'light')
      mq.addEventListener('change', handler)
      return () => mq.removeEventListener('change', handler)
    } else {
      setTheme(mode)
    }
  }, [mode])

  useEffect(() => {
    const root = document.documentElement
    if (theme === 'dark') {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
  }, [theme])

  const setMode = (m: ThemeMode) => {
    setModeState(m)
    localStorage.setItem('hotelsync-theme', m)
  }

  const toggle = () => {
    const next: ThemeMode = mode === 'light' ? 'dark' : mode === 'dark' ? 'auto' : 'light'
    setMode(next)
  }

  return (
    <ThemeContext.Provider value={{ mode, theme, setMode, toggle }}>
      {children}
    </ThemeContext.Provider>
  )
}

export function useTheme() {
  const ctx = useContext(ThemeContext)
  if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
  return ctx
}
