import React from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { sfx } from '../utils/audio'
import { getLS, setLS, KEYS, getUser, getRole, setUser, setRole } from '../utils/storage'
import SwitchAccountsModal from './SwitchAccountsModal'
import { useColorBlindness } from '../context/ColorBlindnessContext'

function ColorBlindnessNavToggle() {
  const { isEnabled, setIsEnabled, type } = useColorBlindness()
  if (type === 'none') return null

  return (
    <button
      onClick={() => { setIsEnabled(!isEnabled); sfx.play('click') }}
      className={`rounded-full px-3 py-2 text-sm font-bold ui border-2 flex items-center gap-2 transition-all ${isEnabled
        ? 'bg-indigo-100 text-indigo-700 border-indigo-200 shadow-sm'
        : 'bg-slate-100 text-slate-400 border-slate-200 grayscale'
        }`}
      title={isEnabled ? "Matikan Mode Buta Warna" : "Hidupkan Mode Buta Warna"}
    >
      <span>{isEnabled ? '👁️' : '🙈'}</span>
      <span className="hidden sm:inline">{isEnabled ? 'Mode Buta Warna: ON' : 'Mode Buta Warna: OFF'}</span>
    </button>
  )
}

export default function TopNav() {
  const [query, setQuery] = React.useState('')
  const [user, setUserState] = React.useState(getUser())
  const [role, setRoleState] = React.useState(getRole())
  const navigate = useNavigate()
  const [menuOpen, setMenuOpen] = React.useState(false)
  const [switchOpen, setSwitchOpen] = React.useState(false)



  return (
    <>
      <header className="sticky top-0 z-40 bg-white/90 backdrop-blur border-b border-onme-softBlue">
        <div className="px-4 sm:px-6 lg:px-8 h-16 flex items-center gap-3">
          <Link to="/" className="heading text-2xl text-onme-blue font-bold tracking-wide" aria-label="KlungKlung beranda">
            KlungKlung
          </Link>
          <form className="flex-1 max-w-xs" onSubmit={e => { e.preventDefault(); sfx.play('click'); navigate('/?q=' + encodeURIComponent(query)) }}>
            <label className="sr-only" htmlFor="search">Cari kelas</label>
            <input id="search" value={query} onChange={e => setQuery(e.target.value)} placeholder="Cari kelas…" className="ui w-full rounded-full px-4 py-2 bg-white border-2 border-onme-softBlue focus:border-onme-blue text-sm" />
          </form>
          <nav className="flex items-center gap-2 relative">
            <ColorBlindnessNavToggle />
            {user ? (
              <>
                <Link to="/profile" className="ui text-sm font-bold text-onme-blue hover:underline px-2">
                  {user.name || 'User'}
                </Link>
                <button
                  aria-label="Settings"
                  onClick={() => { setMenuOpen(o => !o); sfx.play('click') }}
                  className="ui rounded-full bg-white border-2 border-onme-softBlue px-3 py-2 text-lg"
                >
                  ⚙️
                </button>
                {menuOpen && (
                  <div className="absolute right-0 top-12 w-56 bg-white text-gray-800 rounded-xl shadow-xl p-2 z-50 border-2 border-onme-softBlue">
                    <button onClick={() => { sfx.play('click'); setMenuOpen(false); navigate('/settings') }} className="ui text-base w-full text-left px-3 py-2 rounded-lg hover:bg-gray-50 focus-visible:outline-2 focus-visible:outline focus-visible:outline-onme-lime">Settings</button>
                    <button onClick={() => { sfx.play('click'); setMenuOpen(false); setSwitchOpen(true) }} className="ui text-base w-full text-left px-3 py-2 rounded-lg hover:bg-gray-50 focus-visible:outline-2 focus-visible:outline focus-visible:outline-onme-lime">Switch Accounts</button>
                    <button onClick={() => { setUser(null); setRole(null); setUserState(null); setRoleState(null); sfx.play('click'); setMenuOpen(false); navigate('/auth') }} className="ui text-base w-full text-left px-3 py-2 rounded-lg hover:bg-gray-50 focus-visible:outline-2 focus-visible:outline focus-visible:outline-onme-lime">Logout</button>
                  </div>
                )}
              </>
            ) : (
              <Link to="/auth" className="ui rounded-full bg-white border-2 border-onme-softBlue px-4 py-2 text-sm">Masuk</Link>
            )}
          </nav>
        </div>
      </header>
      <SwitchAccountsModal
        open={switchOpen}
        onClose={() => setSwitchOpen(false)}
        onSwitched={(u) => { setUserState(u); setRoleState(u?.role || null) }}
      />
    </>
  )
}
