import { useEffect, useState } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { api } from "./api";
import { DirtyProvider } from "./DirtyContext";
import Layout from "./components/Layout";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
import Users from "./pages/Users";
import Samba from "./pages/Samba";
import Nfs from "./pages/Nfs";
import Log from "./pages/Log";
import Settings from "./pages/Settings";
import Files from "./pages/Files";

type AuthState = { loading: boolean; authenticated: boolean; username: string };

export default function App() {
  const [auth, setAuth] = useState<AuthState>({ loading: true, authenticated: false, username: "" });

  useEffect(() => {
    api
      .status()
      .then((res) => setAuth({ loading: false, authenticated: res.authenticated, username: res.username }))
      .catch(() => setAuth({ loading: false, authenticated: false, username: "" }));
  }, []);

  if (auth.loading) {
    return <div className="flex min-h-screen items-center justify-center text-slate-400">Cargando...</div>;
  }

  if (!auth.authenticated) {
    return (
      <Routes>
        <Route
          path="/login"
          element={<Login onLoggedIn={(username) => setAuth({ loading: false, authenticated: true, username })} />}
        />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    );
  }

  return (
    <DirtyProvider>
      <Routes>
        <Route
          element={
            <Layout
              username={auth.username}
              onLogout={() => setAuth({ loading: false, authenticated: false, username: "" })}
            />
          }
        >
          <Route path="/" element={<Dashboard />} />
          <Route path="/users" element={<Users />} />
          <Route path="/files" element={<Files />} />
          <Route path="/samba" element={<Samba />} />
          <Route path="/nfs" element={<Nfs />} />
          <Route path="/log" element={<Log />} />
          <Route path="/settings" element={<Settings />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Route>
      </Routes>
    </DirtyProvider>
  );
}
