import React from 'react'
import { NavLink, Outlet, useNavigate } from 'react-router-dom'
import { getAdminToken, setAdminToken } from '../../utils/api'

function navClass({ isActive }) {
  return `px-3 py-2 rounded-md text-sm font-medium ${isActive ? 'bg-slate-800 text-white' : 'text-slate-200 hover:bg-slate-800 hover:text-white'}`
}

export default function AdminLayout() {
  const navigate = useNavigate()
  const token = getAdminToken()

  const handleLogout = () => {
    setAdminToken('')
    navigate('/admin/login', { replace: true })
  }

  return (
    <div className="min-h-screen bg-slate-100">
      <header className="bg-slate-900 text-white">
        <div className="max-w-6xl mx-auto px-6 py-4 flex flex-wrap items-center justify-between gap-4">
          <NavLink to="/admin/events" className="text-lg font-semibold tracking-tight">
            Annaville SDA Admin
          </NavLink>
          <nav className="flex items-center gap-3">
            <NavLink to="/" className={navClass}>
              Home
            </NavLink>
            <NavLink to="/admin/events" className={navClass}>
              Events
            </NavLink>
            <NavLink to="/admin/events/new" className={navClass}>
              Add Event
            </NavLink>
            {token ? (
              <button type="button" className="btn" onClick={handleLogout}>
                Log out
              </button>
            ) : (
              <NavLink to="/admin/login" className={navClass}>
                Log in
              </NavLink>
            )}
          </nav>
        </div>
      </header>
      <main className="max-w-6xl mx-auto px-6 py-10">
        <Outlet />
      </main>
    </div>
  )
}
