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 type { Flight } from '../types'

export default function Header() {
  const { t } = useTranslation()
  const { user, logout, hasPermission } = useAuth()
  const { flights, selectedFlight, selectFlight } = useFlight()
  const navigate = useNavigate()
  const [showDropdown, setShowDropdown] = useState(false)
  const [filter, setFilter] = useState('')
  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' },
  ]

  return (
    <header
      className="flex items-center px-4 gap-3 shrink-0"
      style={{ background: 'var(--surface-1)', borderBottom: '1px solid var(--border-hair)', height: 48 }}
    >
      <span
        className="mono font-bold"
        style={{ color: 'var(--accent-amber)', letterSpacing: '0.2em', fontSize: 14 }}
      >
        AZAION
      </span>

      <span className="micro" style={{ color: 'var(--text-muted)' }}>//</span>

      <div className="relative" ref={dropdownRef}>
        <button
          onClick={() => setShowDropdown(!showDropdown)}
          className="inline-flex items-center gap-2 mono"
          style={{
            height: 28,
            padding: '0 10px',
            background: 'var(--surface-1)',
            border: '1px solid var(--accent-amber)',
            borderRadius: 2,
            fontSize: 11,
            letterSpacing: '0.10em',
            minWidth: 140,
          }}
        >
          <span
            className="dot live"
            style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: 'var(--accent-cyan)' }}
          />
          <span style={{ color: 'var(--text-primary)' }}>{selectedFlight?.name || '— SELECT —'}</span>
          <span style={{ color: 'var(--text-secondary)', fontSize: 10 }}>▾</span>
        </button>
        {showDropdown && (
          <div
            className="absolute top-full left-0 mt-1 shadow-lg z-50 w-64"
            style={{ background: 'var(--surface-1)', border: '1px solid var(--border-hair)', borderRadius: 2 }}
          >
            <input
              className="w-full outline-none"
              style={{
                background: 'var(--surface-input)',
                borderBottom: '1px solid var(--border-hair)',
                color: 'var(--text-primary)',
                padding: '6px 10px',
                fontSize: 12,
              }}
              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"
                  style={{
                    padding: '6px 10px',
                    background: selectedFlight?.id === f.id ? 'var(--surface-2)' : 'transparent',
                    color: 'var(--text-primary)',
                    fontSize: 12,
                  }}
                >
                  <div>{f.name}</div>
                  <div className="mono tnum" style={{ fontSize: 10, color: 'var(--text-muted)' }}>
                    {new Date(f.createdDate).toLocaleDateString()}
                  </div>
                </button>
              ))}
              {filtered.length === 0 && (
                <div className="micro" style={{ padding: '8px 10px' }}>No flights</div>
              )}
            </div>
          </div>
        )}
      </div>

      <nav className="hidden sm:flex items-center self-stretch ml-3">
        {navItems.filter(n => hasPermission(n.perm)).map(n => (
          <NavLink
            key={n.to}
            to={n.to}
            className={({ isActive }) => `tab${isActive ? ' active' : ''}`}
          >
            {n.label}
          </NavLink>
        ))}
      </nav>

      <div className="flex items-center gap-2 ml-auto micro">
        <span
          className="dot live"
          style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: 'var(--accent-cyan)' }}
        />
        <span style={{ color: 'var(--accent-cyan)' }}>LINK</span>
        <span style={{ color: 'var(--border-raised)' }}>|</span>
        <span
          className="hidden md:inline"
          style={{ color: 'var(--text-secondary)', textTransform: 'none', letterSpacing: 0 }}
        >
          {user?.email}
        </span>
        <span style={{ color: 'var(--border-raised)', margin: '0 4px' }} className="hidden md:inline">|</span>
        <NavLink to="/settings" className="ibtn" aria-label={t('nav.settings')} title={t('nav.settings')}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M12 15a3 3 0 100-6 3 3 0 000 6z" />
            <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09a1.65 1.65 0 00-1-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09a1.65 1.65 0 001.51-1 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 114 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z" />
          </svg>
        </NavLink>
        <button onClick={handleLogout} className="ibtn danger" aria-label={t('nav.logout')} title={t('nav.logout')}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4" />
            <polyline points="16 17 21 12 16 7" />
            <line x1="21" y1="12" x2="9" y2="12" />
          </svg>
        </button>
      </div>

      {/* Mobile bottom nav */}
      <nav
        className="sm:hidden fixed bottom-0 left-0 right-0 flex justify-around z-50"
        style={{ background: 'var(--surface-1)', borderTop: '1px solid var(--border-hair)', padding: '6px 0' }}
      >
        {navItems.filter(n => hasPermission(n.perm)).map(n => (
          <NavLink
            key={n.to}
            to={n.to}
            className={({ isActive }) =>
              `micro px-2 py-1 ${isActive ? '' : ''}`
            }
            style={({ isActive }) => ({
              color: isActive ? 'var(--accent-amber)' : 'var(--text-muted)',
              fontWeight: isActive ? 600 : 400,
            })}
          >
            {n.label}
          </NavLink>
        ))}
        <NavLink
          to="/settings"
          className="micro px-2 py-1"
          style={({ isActive }) => ({ color: isActive ? 'var(--accent-amber)' : 'var(--text-muted)' })}
        >
          ⚙
        </NavLink>
      </nav>
    </header>
  )
}
