import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export type ThemeMode = 'light' | 'dark' | 'system'
export type AccentKey = 'green' | 'blue' | 'purple' | 'amber' | 'teal' | 'custom'

export const ACCENT_PRESETS: { key: AccentKey; label: string; hex: string }[] = [
  { key: 'green',  label: 'Schaeffler Green', hex: '#00893d' },
  { key: 'blue',   label: 'Blue',             hex: '#2563eb' },
  { key: 'purple', label: 'Purple',           hex: '#7c3aed' },
  { key: 'amber',  label: 'Amber',            hex: '#d97706' },
  { key: 'teal',   label: 'Teal',             hex: '#0d9488' },
]

/** Parse hex color to RGB components */
function hexToRgb(hex: string): [number, number, number] {
  const h = hex.replace('#', '')
  return [
    parseInt(h.substring(0, 2), 16),
    parseInt(h.substring(2, 4), 16),
    parseInt(h.substring(4, 6), 16),
  ]
}

/** Darken a hex color by a factor (0-1) */
function darken(hex: string, amount: number): string {
  const [r, g, b] = hexToRgb(hex)
  const f = 1 - amount
  return `#${Math.round(r * f).toString(16).padStart(2, '0')}${Math.round(g * f).toString(16).padStart(2, '0')}${Math.round(b * f).toString(16).padStart(2, '0')}`
}

/** Lighten a hex color to a pastel (for light theme accent-light) */
function lighten(hex: string, amount: number): string {
  const [r, g, b] = hexToRgb(hex)
  const f = amount
  return `#${Math.round(r + (255 - r) * f).toString(16).padStart(2, '0')}${Math.round(g + (255 - g) * f).toString(16).padStart(2, '0')}${Math.round(b + (255 - b) * f).toString(16).padStart(2, '0')}`
}

/** Apply custom accent color CSS variables directly to :root */
function applyCustomAccent(hex: string) {
  const root = document.documentElement
  const [r, g, b] = hexToRgb(hex)
  const isDark = root.classList.contains('dark')

  root.style.setProperty('--color-accent', hex)
  root.style.setProperty('--color-accent-hover', darken(hex, 0.2))
  root.style.setProperty('--color-accent-light', isDark
    ? `rgba(${r}, ${g}, ${b}, 0.12)`
    : lighten(hex, 0.85)
  )
  root.style.setProperty('--color-accent-text', '#ffffff')
}

/** Clear custom accent CSS variables (revert to preset-driven) */
function clearCustomAccent() {
  const root = document.documentElement
  root.style.removeProperty('--color-accent')
  root.style.removeProperty('--color-accent-hover')
  root.style.removeProperty('--color-accent-light')
  root.style.removeProperty('--color-accent-text')
}

interface ThemeState {
  mode: ThemeMode
  accent: AccentKey
  customHex: string
  setMode: (mode: ThemeMode) => void
  setAccent: (accent: AccentKey) => void
  setCustomHex: (hex: string) => void
}

/** Returns 'light' | 'dark' based on mode + system preference */
export function resolveTheme(mode: ThemeMode): 'light' | 'dark' {
  if (mode === 'system') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }
  return mode
}

/** Applies theme to <html> element */
export function applyTheme(mode: ThemeMode, accent: AccentKey, customHex?: string) {
  const resolved = resolveTheme(mode)
  const html = document.documentElement
  if (resolved === 'dark') {
    html.classList.add('dark')
  } else {
    html.classList.remove('dark')
  }

  if (accent === 'custom' && customHex) {
    html.setAttribute('data-accent', 'custom')
    applyCustomAccent(customHex)
  } else {
    html.setAttribute('data-accent', accent)
    clearCustomAccent()
  }
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      mode: 'light',
      accent: 'green',
      customHex: '#6366f1',
      setMode: (mode) => {
        set({ mode })
        applyTheme(mode, get().accent, get().customHex)
      },
      setAccent: (accent) => {
        set({ accent })
        applyTheme(get().mode, accent, get().customHex)
      },
      setCustomHex: (hex) => {
        set({ customHex: hex, accent: 'custom' })
        applyTheme(get().mode, 'custom', hex)
      },
    }),
    { name: 'schaeffler-theme' },
  ),
)
