import { Box, CircularProgress } from "@mui/material";
import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router-dom";

import Layout from "./components/Layout";
import { useAuth } from "./contexts/AuthContext";
import CalendarView from "./routes/CalendarView";
import ContractDetail from "./routes/ContractDetail";
import ContractForm from "./routes/ContractForm";
import ContractsList from "./routes/ContractsList";
import Dashboard from "./routes/Dashboard";
import LoginPage from "./routes/Login";
import SettingsPage from "./routes/Settings";

function ProtectedRoute({ children }: { children: JSX.Element }) {
  const { isAuthenticated, loading } = useAuth();
  const location = useLocation();

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="60vh">
        <CircularProgress />
      </Box>
    );
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route
          path="/"
          element={
            <ProtectedRoute>
              <Layout />
            </ProtectedRoute>
          }
        >
          <Route index element={<Navigate to="/dashboard" replace />} />
          <Route path="dashboard" element={<Dashboard />} />
          <Route path="contracts" element={<ContractsList />} />
          <Route path="contracts/new" element={<ContractForm mode="create" />} />
          <Route path="contracts/:contractId" element={<ContractDetail />} />
          <Route path="contracts/:contractId/edit" element={<ContractForm mode="edit" />} />
          <Route path="calendar" element={<CalendarView />} />
          <Route path="settings" element={<SettingsPage />} />
        </Route>
        <Route path="*" element={<Navigate to="/dashboard" replace />} />
      </Routes>
    </BrowserRouter>
  );
}
