import React, { useEffect, useState } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { getSessionUser } from "./api/userApi";
import Layout from "./components/Layout";
import Dashboard from "./pages/Dashboard";
import Login from "./pages/Login";
import Supplier from "./pages/Supplier";
import Shipment from "./pages/Shipment";
import Delivery from "./pages/Delivery";
import Reports from "./pages/Reports";
import Logout from "./pages/Logout";

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

  return props.children;
}

function App() {
  var userState = useState(null);
  var user = userState[0];
  var setUser = userState[1];
  var checkingSessionState = useState(true);
  var checkingSession = checkingSessionState[0];
  var setCheckingSession = checkingSessionState[1];

  useEffect(function () {
    getSessionUser()
      .then(function (response) {
        setUser(response.data.user);
      })
      .catch(function () {
        setUser(null);
      })
      .finally(function () {
        setCheckingSession(false);
      });
  }, []);

  if (checkingSession) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-slate-50 text-blue-900">
        Loading SCMS...
      </div>
    );
  }

  return (
    <Routes>
      <Route path="/login" element={<Login setUser={setUser} />} />
      <Route
        path="/"
        element={
          <ProtectedRoute user={user}>
            <Layout user={user} />
          </ProtectedRoute>
        }
      >
        <Route index element={<Dashboard />} />
        <Route path="suppliers" element={<Supplier />} />
        <Route path="shipments" element={<Shipment />} />
        <Route path="deliveries" element={<Delivery />} />
        <Route path="reports" element={<Reports />} />
        <Route path="logout" element={<Logout setUser={setUser} />} />
      </Route>
    </Routes>
  );
}

export default App;
