import { createBrowserRouter, RouterProvider, Navigate, Outlet } from "react-router-dom"
import { ThemeProvider } from "./components/ThemeProvider"
import { LanguageProvider } from "./components/LanguageProvider"
import { Toaster } from "./components/ui/toaster"
import { Navbar } from "./components/Navbar"
import { Sidebar } from './components/Sidebar';
import { WorkspaceProvider } from "./context/WorkspaceContext"
import Auth from "./pages/Auth"
import Profile from "./pages/Profile"
import Terms from "./pages/Terms"
import Workspaces from "./pages/Workspaces"
import CreateWorkspace from "./pages/WorkspaceCreate"
import WorkspaceDetail from "./pages/WorkspaceDetail"
import EditWorkspace from "./pages/WorkspaceEdit"
import Clients from "./pages/Clients"
import { Projects } from "./pages/Projects"
import ProjectCreate from "./pages/ProjectCreate"
import ProjectEdit from "./pages/ProjectEdit"
import Tags from "./pages/Tags"
import Timesheet from "./pages/Timesheet"

const MainLayout = () => {
  return (
    <div className="flex h-screen bg-slate-50 dark:bg-slate-950 overflow-hidden text-slate-900 dark:text-slate-100">
      <Sidebar />

      <div className="flex-1 flex flex-col h-screen overflow-y-auto relative">
        <Navbar />

        <main className="flex-1 relative">
          <Outlet />
        </main>
      </div>
    </div>
  );
};

const RootRedirect = () => {
  const isAuthenticated = !!localStorage.getItem("accessToken")  
  return isAuthenticated ? <Navigate to="/timesheet" replace /> : <Navigate to="/auth" replace />
}

const router = createBrowserRouter([
  {
    element: (
      <WorkspaceProvider>
        <Outlet />
      </WorkspaceProvider>
    ),
    children: [
      { path: "/", element: <RootRedirect /> },
      { path: "/auth", element: <Auth /> },
      { path: "/terms", element: <Terms /> },
      {
        element: <MainLayout />,
        children: [
          { path: "/profile", element: <Profile /> },
          { path: "/timesheet", element: <Timesheet /> },
          { path: "/tags", element: <Tags /> },
          { path: "/workspaces", element: <Workspaces /> },
          { path: "/workspaces/create", element: <CreateWorkspace /> },
          { path: "/workspaces/:id", element: <WorkspaceDetail /> },
          { path: "/workspaces/:id/edit", element: <EditWorkspace /> },
          { path: "/clients", element: <Clients /> },
          { path: "/projects", element: <Projects /> },
          { path: "/projects/create", element: <ProjectCreate /> },
          { path: "/projects/:id/edit", element: <ProjectEdit /> },
        ],
      },
    ],
  },
]);

function App() {
  return (
    <ThemeProvider>
      <LanguageProvider>
        <RouterProvider router={router} />
        <Toaster />
      </LanguageProvider>
    </ThemeProvider>
  )
}

export default App
