import { useRef } from 'react'
import {
  Field,
  Button,
  Card,
  Subtitle2,
  Caption1,
  Switch,
  mergeClasses
} from '@fluentui/react-components'
import { PaintBucketRegular, AccessibilityRegular } from '@fluentui/react-icons'
import { type ThemeMode, type AccentColor } from '@shared/ipc'
import { useSettings } from '../../store/settings'
import { useSystemTheme } from '../../store/systemTheme'
import { Select } from '../../components/Select'
import { ACCENT_OPTIONS } from '../../lib/theme'
import { useFocusStyles } from '../../components/ui/focusRing'
import { useSettingsStyles } from './settingsStyles'

const THEME_MODE_OPTIONS = [
  { value: 'light', label: 'Light' },
  { value: 'dark', label: 'Dark' },
  { value: 'system', label: 'Follow system' }
]

export function AppearanceCard(): React.JSX.Element {
  const styles = useSettingsStyles()
  const focus = useFocusStyles()
  const theme = useSettings((s) => s.theme)
  const accentColor = useSettings((s) => s.accentColor)
  const useHardwareAcceleration = useSettings((s) => s.useHardwareAcceleration)
  const highContrast = useSystemTheme((s) => s.shouldUseHighContrastColors)
  const update = useSettings((s) => s.update)
  // Store action wraps the IPC call (L93/CC13: no window.api in components).
  const openHighContrastSettings = useSettings((s) => s.openHighContrastSettings)

  // Roving-tabindex arrow-key navigation for the accent radiogroup (L155), so the
  // single-select swatches behave like the Theme radio pattern rather than a row
  // of plain buttons.
  const swatchRefs = useRef<(HTMLButtonElement | null)[]>([])
  function onSwatchKey(e: React.KeyboardEvent, index: number): void {
    const n = ACCENT_OPTIONS.length
    let next = -1
    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = (index + 1) % n
    else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = (index - 1 + n) % n
    else if (e.key === 'Home') next = 0
    else if (e.key === 'End') next = n - 1
    else return
    const opt = ACCENT_OPTIONS[next]
    if (!opt) return
    e.preventDefault()
    update({ accentColor: opt.value as AccentColor })
    swatchRefs.current[next]?.focus()
  }

  return (
    <Card className={styles.card}>
      <div className={styles.sectionHeader}>
        <PaintBucketRegular className={styles.sectionIcon} />
        <Subtitle2 as="h3">Appearance</Subtitle2>
      </div>

      <Field label="Theme">
        <Select
          value={theme}
          options={THEME_MODE_OPTIONS}
          onChange={(v) => update({ theme: v as ThemeMode })}
        />
      </Field>

      <Field label="Accent color">
        <div className={styles.swatchRow} role="radiogroup" aria-label="Accent color">
          {ACCENT_OPTIONS.map((opt, i) => {
            const selected = accentColor === opt.value
            return (
              <button
                key={opt.value}
                ref={(el) => {
                  swatchRefs.current[i] = el
                }}
                type="button"
                role="radio"
                aria-checked={selected}
                // Roving tabindex: only the selected swatch is a tab stop; arrows
                // move within the group (L155).
                tabIndex={selected ? 0 : -1}
                className={mergeClasses(
                  styles.swatch,
                  selected && styles.swatchActive,
                  focus.focusRing
                )}
                style={{ backgroundColor: opt.swatch }}
                onClick={() => update({ accentColor: opt.value as AccentColor })}
                onKeyDown={(e) => onSwatchKey(e, i)}
                aria-label={opt.label}
                title={opt.label}
              />
            )
          })}
        </div>
      </Field>

      <Field
        label="Hardware acceleration"
        hint="Uses the GPU to draw the window (takes effect after you restart AeroFetch). Off by default: some older GPUs render the window blank with this on — turn it back off if that happens."
      >
        <Switch
          checked={useHardwareAcceleration}
          onChange={(_, d) => update({ useHardwareAcceleration: d.checked })}
        />
      </Field>

      <Caption1 className={styles.hint}>
        {highContrast
          ? 'A Windows high-contrast theme is active -- AeroFetch follows your system colors.'
          : 'AeroFetch automatically follows a Windows high-contrast theme if you turn one on.'}
      </Caption1>
      {highContrast && (
        <div className={styles.folderRow}>
          <Button size="small" icon={<AccessibilityRegular />} onClick={openHighContrastSettings}>
            Open accessibility settings
          </Button>
        </div>
      )}
    </Card>
  )
}
