import {
  BrowserRouter,
  Routes,
  Route,
  Navigate,
  NavLink,
  Outlet,
  useNavigate,
} from 'react-router-dom';
import { useState, useEffect } from 'react';
import { Toaster } from 'sonner';
import {
  Database,
  LayoutDashboard,
  Server,
  GitCompare,
  History,
  Key,
  Settings as SettingsIcon,
  LogOut,
  Menu,
  X,
} from 'lucide-react';
import { ErrorBoundary } from './components/ErrorBoundary';
import { Spinner } from './components/ui/Spinner';
import { Button } from './components/ui/Button';
import { cn } from './lib/utils';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Machines from './pages/Machines';
import SyncPairs from './pages/SyncPairs';
import JobHistory from './pages/JobHistory';
import JobDetail from './pages/JobDetail';
import SettingsPage from './pages/Settings';
import SSHKeys from './pages/SSHKeys';

const navItems = [
  { to: '/', label: 'Dashboard', icon: LayoutDashboard },
  { to: '/machines', label: 'Machines', icon: Server },
  { to: '/sync-pairs', label: 'Sync Pairs', icon: GitCompare },
  { to: '/jobs', label: 'Jobs', icon: History },
  { to: '/ssh-keys', label: 'SSH Keys', icon: Key },
  { to: '/settings', label: 'Settings', icon: SettingsIcon },
];

function ProtectedRoute({ children }: { children: JSX.Element }) {
  const [authed, setAuthed] = useState<boolean | null>(null);
  useEffect(() => {
    fetch('/api/auth/me', { credentials: 'include' })
      .then(r => setAuthed(r.ok))
      .catch(() => setAuthed(false));
  }, []);
  if (authed === null) {
    return (
      <div className="flex h-screen items-center justify-center bg-canvas">
        <Spinner size="lg" />
      </div>
    );
  }
  return authed ? children : <Navigate to="/login" />;
}

function NavBar() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const navigate = useNavigate();

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
    } catch {}
    localStorage.removeItem('auth');
    navigate('/login');
  };

  return (
    <header className="sticky top-0 z-50 bg-surface border-b border-border">
      <div className="max-w-7xl mx-auto px-4">
        <div className="flex items-center h-14 gap-6">
          <a
            href="/"
            className="flex items-center gap-2.5 text-fg font-bold text-base hover:text-accent transition-colors shrink-0"
          >
            <div className="rounded-card bg-accent/10 p-1">
              <Database className="h-4 w-4 text-accent" />
            </div>
            <span className="hidden sm:inline">SyncServer</span>
          </a>

          <nav className="hidden md:flex items-center gap-0.5 flex-1">
            {navItems.map(item => {
              const Icon = item.icon;
              return (
                <NavLink
                  key={item.to}
                  to={item.to}
                  end={item.to === '/'}
                  className={({ isActive }) =>
                    cn(
                      'flex items-center gap-1.5 px-3 py-1.5 rounded-card text-sm font-medium transition-all duration-150',
                      isActive
                        ? 'bg-surface-raised text-fg'
                        : 'text-fg-muted hover:text-fg hover:bg-surface-raised'
                    )
                  }
                >
                  <Icon className="h-3.5 w-3.5" />
                  {item.label}
                </NavLink>
              );
            })}
          </nav>

          <div className="flex items-center gap-2 ml-auto">
            <Button
              variant="ghost"
              size="icon-sm"
              onClick={handleLogout}
              className="text-fg-muted hover:text-fg hidden sm:flex"
              title="Logout"
            >
              <LogOut className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setMobileOpen(v => !v)}
              className="md:hidden text-fg-muted"
            >
              {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
            </Button>
          </div>
        </div>

        {mobileOpen && (
          <nav className="md:hidden pb-3 flex flex-col gap-0.5 animate-slide-up">
            {navItems.map(item => {
              const Icon = item.icon;
              return (
                <NavLink
                  key={item.to}
                  to={item.to}
                  end={item.to === '/'}
                  onClick={() => setMobileOpen(false)}
                  className={({ isActive }) =>
                    cn(
                      'flex items-center gap-2 px-3 py-2 rounded-card text-sm font-medium transition-all',
                      isActive
                        ? 'bg-surface-raised text-fg'
                        : 'text-fg-muted hover:text-fg hover:bg-surface-raised'
                    )
                  }
                >
                  <Icon className="h-4 w-4" />
                  {item.label}
                </NavLink>
              );
            })}
            <button
              onClick={() => {
                setMobileOpen(false);
                handleLogout();
              }}
              className="flex items-center gap-2 px-3 py-2 rounded-card text-sm font-medium text-fg-muted hover:text-fg hover:bg-surface-raised mt-1 border-t border-border pt-3"
            >
              <LogOut className="h-4 w-4" />
              Logout
            </button>
          </nav>
        )}
      </div>
    </header>
  );
}

function Layout() {
  return (
    <div className="min-h-screen bg-canvas">
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:rounded-card focus:bg-surface-raised focus:text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"
      >
        Skip to content
      </a>
      <NavBar />
      <main id="main-content" className="max-w-7xl mx-auto px-4 py-6">
        <Outlet />
      </main>
      <Toaster
        position="bottom-right"
        toastOptions={{
          classNames: {
            error: 'bg-surface-raised border border-rose-500/30 text-fg',
            success: 'bg-surface-raised border border-emerald-500/30 text-fg',
            warning: 'bg-surface-raised border border-amber-500/30 text-fg',
            info: 'bg-surface-raised border border-sky-500/30 text-fg',
          },
        }}
        theme="dark"
        richColors
        closeButton
      />
    </div>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <ErrorBoundary>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route
            element={
              <ProtectedRoute>
                <Layout />
              </ProtectedRoute>
            }
          >
            <Route path="/" element={<Dashboard />} />
            <Route path="/machines" element={<Machines />} />
            <Route path="/sync-pairs" element={<SyncPairs />} />
            <Route path="/jobs" element={<JobHistory />} />
            <Route path="/jobs/:id" element={<JobDetail />} />
            <Route path="/ssh-keys" element={<SSHKeys />} />
            <Route path="/settings" element={<SettingsPage />} />
          </Route>
          <Route path="*" element={<Navigate to="/" />} />
        </Routes>
      </ErrorBoundary>
    </BrowserRouter>
  );
}
