import { NavLink, Navigate, Route, Routes } from "react-router-dom";
import { AuthProvider, useAuth } from "./contexts/AuthContext";
import AlbumsPage from "./pages/AlbumsPage";
import UsersPage from "./pages/UsersPage";
import AlbumTracksPage from "./pages/AlbumTracksPage";
import LoginPage from "./pages/LoginPage";

function ProtectedRoute({ children }) {
  const { token, loading } = useAuth();

  if (loading) return <p>Loading...</p>;
  if (!token) return <Navigate to="/login" replace />;

  return children;
}

function AppLayout() {
  const { user, logout } = useAuth();

  return (
    <div className="app">
      <header className="topbar card">
        <h1>Admin Panel</h1>
        <nav className="nav">
          <NavLink to="/albums" className={({ isActive }) => isActive ? "tab active" : "tab"}>
            Albums
          </NavLink>
          <NavLink to="/users" className={({ isActive }) => isActive ? "tab active" : "tab"}>
            Users
          </NavLink>
          <button className="tab logout" onClick={logout}>
            Logout ({user?.name})
          </button>
        </nav>
      </header>

      <main className="content">
        <Routes>
          <Route path="/" element={<Navigate to="/albums" replace />} />
          <Route path="/albums" element={<AlbumsPage />} />
          <Route path="/users" element={<UsersPage />} />
          <Route path="/albums/:albumId/tracks" element={<AlbumTracksPage />} />
        </Routes>
      </main>
    </div>
  );
}

export default function App() {
  return (
    <AuthProvider>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/*" element={
          <ProtectedRoute>
            <AppLayout />
          </ProtectedRoute>
        } />
      </Routes>
    </AuthProvider>
  );
}
