import { useEffect, useState } from 'react'
import { NavLink, Outlet, useNavigate } from 'react-router-dom'
import { Icon } from '../components/Icon'
import { CommandPalette } from './CommandPalette'

export const NAV = [
  { to: '/', icon: 'home', label: 'Dashboard', end: true },
  { to: '/tasks', icon: 'task', label: 'Tasks' },
  { to: '/decisions', icon: 'decision', label: 'Decisions' },
  { to: '/workers', icon: 'worker', label: 'Workers' },
  { to: '/projects', icon: 'project', label: 'Projects' },
  { to: '/review', icon: 'review', label: 'Review' },
  { to: '/settings', icon: 'settings', label: 'Settings', secondary: true },
]

/** Machine readouts belong in the top bar on desktop. On mobile they relocate
 *  into the detail screens rather than disappearing: honesty moves, it is
 *  never deleted. */
function Clock() {
  const [now, setNow] = useState(() => new Date())
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000)
    return () => clearInterval(id)
  }, [])
  return <span>{now.toISOString().slice(11, 19)} UTC</span>
}

export function Shell({ revision, live }: { revision?: string; live?: boolean }) {
  const [palette, setPalette] = useState(false)
  const navigate = useNavigate()

  useEffect(() => {
    const onShortcut = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
        event.preventDefault()
        setPalette((open) => !open)
      }
      if (event.key === 'Escape') setPalette(false)
    }
    window.addEventListener('keydown', onShortcut)
    return () => window.removeEventListener('keydown', onShortcut)
  }, [])

  return (
    <div className="console shell">
      <nav className="rail" aria-label="Primary">
        <span className="rail-mark">
          <Icon name="fork" size={26} />
        </span>
        {NAV.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            end={item.end}
            className="rail-item"
            data-secondary={item.secondary ? 'true' : undefined}
            title={item.label}
            aria-label={item.label}
          >
            <Icon name={item.icon} />
          </NavLink>
        ))}
        <span className="rail-spacer" />
      </nav>
      <div className="main">
        <header className="topbar">
          <span className="topbar-title">orchestra</span>
          <button className="cmdk-trigger" onClick={() => setPalette(true)}>
            <kbd>⌘K</kbd>
            <span>Search tasks, decisions, workers…</span>
          </button>
          <div className="topbar-readouts">
            {revision && <span title={revision}>{revision.slice(0, 7)}</span>}
            <span>
              <span className="dot" data-health={live ? 'healthy' : 'unknown'} />{' '}
              {live ? 'Live' : 'Unknown'}
            </span>
            <Clock />
          </div>
        </header>
        <Outlet />
      </div>
      {palette && (
        <CommandPalette
          onClose={() => setPalette(false)}
          onNavigate={(to) => {
            setPalette(false)
            navigate(to)
          }}
        />
      )}
    </div>
  )
}
