import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom';

import { Button } from '@/components/ui/Button';
import { useAuth } from '@/lib/auth';
import { cn } from '@/lib/cn';

export function Layout() {
  const { state, logout } = useAuth();
  const navigate = useNavigate();

  const navItem = (to: string, label: string) => (
    <NavLink
      to={to}
      end
      className={({ isActive }) =>
        cn(
          'font-mono text-xs uppercase tracking-wider2 px-3 py-1 rounded',
          isActive ? 'text-cyan accent-fill-cyan' : 'text-text-dim hover:text-text-bright',
        )
      }
    >
      {label}
    </NavLink>
  );

  return (
    <div className="px-[60px] py-10">
      <div className="mx-auto max-w-page">
        <header className="flex items-baseline justify-between mb-12">
          <Link to="/" className="font-mono text-[24px] font-bold tracking-tight text-text-bright">
            <span className="text-red">Meta</span>
            <span>morph</span>
          </Link>
          <nav className="flex items-center gap-2" aria-label="Primary">
            {state.user ? (
              <>
                {navItem('/', 'Home')}
                {navItem('/profile', 'Profile')}
                {navItem('/mitre', 'MITRE')}
                {(state.user.is_admin ||
                  state.user.permissions.includes('mission.read')) &&
                  navItem('/missions', 'Missions')}
                {state.user.is_admin && (
                  <>
                    {navItem('/admin/users', 'Users')}
                    {navItem('/admin/groups', 'Groups')}
                    {navItem('/admin/invitations', 'Invitations')}
                    {navItem('/admin/tests', 'Tests')}
                    {navItem('/admin/scenarios', 'Scenarios')}
                  </>
                )}
                <span className="font-mono text-2xs text-text-dim ml-2" data-testid="me-email">
                  {state.user.email}
                </span>
                <Button
                  accent="rose"
                  onClick={async () => {
                    await logout();
                    navigate('/login', { replace: true });
                  }}
                >
                  Logout
                </Button>
              </>
            ) : (
              <>
                {navItem('/login', 'Login')}
                {navItem('/setup', 'Setup')}
              </>
            )}
          </nav>
        </header>

        <Outlet />

        <footer className="mt-[60px] py-8 border-t border-border text-center font-mono text-xs text-text-dim">
          metamorph · M0 bootstrap · M1 db schema · M2 auth · M3 rbac · M4 mitre · M5 templates · M6 missions · design system from tasks/design.md
        </footer>
      </div>
    </div>
  );
}
