import { Routes, Route, Navigate } from "react-router-dom";
import { useAuth } from "./auth/AuthContext";
import LoginPage from "./auth/LoginPage";
import MainLayout from "./layout/MainLayout";
import MelodyList from "./melodies/MelodyList";
import MelodyDetail from "./melodies/MelodyDetail";
import MelodyForm from "./melodies/MelodyForm";
import MelodySettings from "./melodies/MelodySettings";
import DeviceList from "./devices/DeviceList";
import DeviceDetail from "./devices/DeviceDetail";
import DeviceForm from "./devices/DeviceForm";

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <p className="text-gray-500">Loading...</p>
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return children;
}

function DashboardPage() {
  const { user } = useAuth();
  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-4">Dashboard</h1>
      <p className="text-gray-600">
        Welcome, {user?.name}. You are logged in as{" "}
        <span className="font-medium">{user?.role}</span>.
      </p>
    </div>
  );
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        element={
          <ProtectedRoute>
            <MainLayout />
          </ProtectedRoute>
        }
      >
        <Route index element={<DashboardPage />} />
        <Route path="melodies" element={<MelodyList />} />
        <Route path="melodies/settings" element={<MelodySettings />} />
        <Route path="melodies/new" element={<MelodyForm />} />
        <Route path="melodies/:id" element={<MelodyDetail />} />
        <Route path="melodies/:id/edit" element={<MelodyForm />} />
        <Route path="devices" element={<DeviceList />} />
        <Route path="devices/new" element={<DeviceForm />} />
        <Route path="devices/:id" element={<DeviceDetail />} />
        <Route path="devices/:id/edit" element={<DeviceForm />} />
        {/* Phase 4+ routes:
        <Route path="users" element={<UserList />} />
        <Route path="mqtt" element={<MqttDashboard />} />
        */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Route>
    </Routes>
  );
}
