import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../../auth/AuthProvider'
import {
  readPortalStylePrefs,
  writePortalStylePrefs,
  type PortalAccent,
  type PortalColorMode,
  type PortalDensity,
  type PortalFontFamily,
  type PortalFontScale,
  type PortalStylePrefs,
} from '../../lib/portalAppearance'
import { isParentPortalRole, isTeacherPortalRole } from '../../lib/portalRoles'

function emitPortalStyleChanged() {
  window.dispatchEvent(new Event('alrahma-portal-style'))
}

export function PortalStylePage() {
  const navigate = useNavigate()
  const { selectedRole, roles } = useAuth()
  const role = selectedRole ?? roles[0] ?? ''
  const backTo =
    isParentPortalRole(role)
      ? '/app/parent/home'
      : isTeacherPortalRole(role)
        ? '/app/teacher_dashboard'
        : '/app/home'

  const [prefs, setPrefs] = useState<PortalStylePrefs>(() => readPortalStylePrefs())

  useEffect(() => {
    writePortalStylePrefs(prefs)
    emitPortalStyleChanged()
  }, [prefs])

  function patch<K extends keyof PortalStylePrefs>(key: K, value: PortalStylePrefs[K]) {
    setPrefs((p) => ({ ...p, [key]: value }))
  }

  return (
    <div className="container py-4" style={{ maxWidth: 560 }}>
      <div className="d-flex align-items-center gap-2 mb-3">
        <button type="button" className="btn btn-outline-secondary btn-sm" onClick={() => navigate(-1)}>
          Back
        </button>
        <button type="button" className="btn btn-link btn-sm p-0" onClick={() => navigate(backTo)}>
          Home
        </button>
      </div>
      <h1 className="h4 mb-1">Style edit</h1>
      <p className="text-muted small mb-4">
        Theme, color, text size, and font apply to the parent and teacher portal on this browser only.
      </p>
      <div className="card border-0 shadow-sm">
        <div className="card-body">
          <div className="mb-4">
            <label className="form-label fw-semibold" htmlFor="portal-color-mode">
              Mode
            </label>
            <select
              id="portal-color-mode"
              className="form-select"
              value={prefs.colorMode}
              onChange={(e) => patch('colorMode', e.target.value as PortalColorMode)}
            >
              <option value="light">Light</option>
              <option value="dark">Dark</option>
              <option value="system">Match system</option>
            </select>
            <p className="form-text small mb-0">
              &quot;Match system&quot; follows your device or browser light/dark setting.
            </p>
          </div>
          <div className="mb-4">
            <label className="form-label fw-semibold" htmlFor="portal-accent">
              Accent color
            </label>
            <select
              id="portal-accent"
              className="form-select"
              value={prefs.accent}
              onChange={(e) => patch('accent', e.target.value as PortalAccent)}
            >
              <option value="default">School green (default)</option>
              <option value="ocean">Ocean teal</option>
              <option value="slate">Slate blue</option>
              <option value="violet">Violet</option>
              <option value="earth">Earth / amber</option>
              <option value="rose">Rose</option>
              <option value="indigo">Indigo</option>
              <option value="sky">Sky blue</option>
              <option value="crimson">Crimson</option>
              <option value="emerald">Emerald</option>
            </select>
          </div>
          <div className="mb-4">
            <label className="form-label fw-semibold" htmlFor="portal-font-scale">
              Text size
            </label>
            <select
              id="portal-font-scale"
              className="form-select"
              value={prefs.fontScale}
              onChange={(e) => patch('fontScale', e.target.value as PortalFontScale)}
            >
              <option value="sm">Smaller</option>
              <option value="normal">Normal</option>
              <option value="large">Large</option>
              <option value="xl">Extra large</option>
            </select>
          </div>
          <div className="mb-4">
            <label className="form-label fw-semibold" htmlFor="portal-font-family">
              Font
            </label>
            <select
              id="portal-font-family"
              className="form-select"
              value={prefs.fontFamily}
              onChange={(e) => patch('fontFamily', e.target.value as PortalFontFamily)}
            >
              <option value="default">Heebo (default)</option>
              <option value="system">System UI</option>
              <option value="readable">Serif (readable)</option>
              <option value="modern">Segoe / Roboto</option>
            </select>
          </div>
          <div className="mb-0">
            <label className="form-label fw-semibold" htmlFor="portal-density">
              Layout density
            </label>
            <select
              id="portal-density"
              className="form-select"
              value={prefs.density}
              onChange={(e) => patch('density', e.target.value as PortalDensity)}
            >
              <option value="comfortable">Comfortable</option>
              <option value="compact">Compact</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  )
}
