import { NavLink, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '../auth'
import { useFlight } from './FlightContext'
import { useState, useRef, useEffect } from 'react'
import HelpModal from './HelpModal'
import type { Flight } from '../types'

export default function Header() {
  const { t, i18n } = useTranslation()
  const { user, logout, hasPermission } = useAuth()
  const { flights, selectedFlight, selectFlight } = useFlight()
  const navigate = useNavigate()
  const [showDropdown, setShowDropdown] = useState(false)
  const [filter, setFilter] = useState('')
  const [showHelp, setShowHelp] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node))
        setShowDropdown(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  const filtered = flights.filter(f => f.name.toLowerCase().includes(filter.toLowerCase()))

  const handleLogout = async () => {
    await logout()
    navigate('/login')
  }

  const navItems = [
    { to: '/flights', label: t('nav.flights'), perm: 'FL' },
    { to: '/annotations', label: t('nav.annotations'), perm: 'ANN' },
    { to: '/dataset', label: t('nav.dataset'), perm: 'DATASET' },
    { to: '/admin', label: t('nav.admin'), perm: 'ADM' },
  ]

  const toggleLang = () => {
    i18n.changeLanguage(i18n.language === 'en' ? 'ua' : 'en')
  }

  return (
    <header className="flex items-center h-10 bg-az-header border-b border-az-border px-3 gap-3 text-sm shrink-0">
      <span className="font-bold text-az-orange tracking-wider">AZAION</span>

      <div className="relative" ref={dropdownRef}>
        <button
          onClick={() => setShowDropdown(!showDropdown)}
          className="bg-az-panel border border-az-border rounded px-2 py-0.5 text-az-text hover:border-az-muted min-w-[160px] text-left truncate"
        >
          {selectedFlight?.name || '— Select Flight —'}
        </button>
        {showDropdown && (
          <div className="absolute top-full left-0 mt-1 bg-az-panel border border-az-border rounded shadow-lg z-50 w-64">
            <input
              className="w-full bg-az-bg border-b border-az-border px-2 py-1 text-az-text text-sm outline-none"
              placeholder="Filter..."
              value={filter}
              onChange={e => setFilter(e.target.value)}
              autoFocus
            />
            <div className="max-h-60 overflow-y-auto">
              {filtered.map((f: Flight) => (
                <button
                  key={f.id}
                  onClick={() => { selectFlight(f); setShowDropdown(false); setFilter('') }}
                  className={`w-full text-left px-2 py-1 hover:bg-az-bg text-az-text text-sm ${
                    selectedFlight?.id === f.id ? 'bg-az-bg font-semibold' : ''
                  }`}
                >
                  <div>{f.name}</div>
                  <div className="text-xs text-az-muted">{new Date(f.createdDate).toLocaleDateString()}</div>
                </button>
              ))}
              {filtered.length === 0 && (
                <div className="px-2 py-2 text-az-muted text-xs">No flights</div>
              )}
            </div>
          </div>
        )}
      </div>

      <nav className="hidden sm:flex items-center gap-1 ml-2">
        {navItems.filter(n => hasPermission(n.perm)).map(n => (
          <NavLink
            key={n.to}
            to={n.to}
            className={({ isActive }) =>
              `px-2 py-1 rounded text-sm ${isActive ? 'bg-az-bg font-semibold text-white' : 'text-az-text hover:text-white'}`
            }
          >
            {n.label}
          </NavLink>
        ))}
      </nav>

      <div className="flex-1" />

      <span className="text-xs text-az-muted hidden sm:block">{user?.email}</span>
      <button onClick={toggleLang} className="text-xs text-az-muted hover:text-white px-1">
        {i18n.language === 'en' ? 'UA' : 'EN'}
      </button>
      <button onClick={() => setShowHelp(true)} className="text-az-muted hover:text-white text-xs">?</button>
      <NavLink to="/settings" className="text-az-muted hover:text-white">⚙</NavLink>
      <button onClick={handleLogout} className="text-az-muted hover:text-az-red text-xs">
        {t('nav.logout')}
      </button>

      {/* Mobile bottom nav */}
      <nav className="sm:hidden fixed bottom-0 left-0 right-0 bg-az-header border-t border-az-border flex justify-around py-1.5 z-50">
        {navItems.filter(n => hasPermission(n.perm)).map(n => (
          <NavLink
            key={n.to}
            to={n.to}
            className={({ isActive }) =>
              `text-xs px-2 py-1 ${isActive ? 'text-az-orange font-semibold' : 'text-az-muted'}`
            }
          >
            {n.label}
          </NavLink>
        ))}
        <NavLink to="/settings" className={({ isActive }) => `text-xs px-2 py-1 ${isActive ? 'text-az-orange' : 'text-az-muted'}`}>
          ⚙
        </NavLink>
      </nav>
      <HelpModal open={showHelp} onClose={() => setShowHelp(false)} />
    </header>
  )
}
