import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
import {
  Login,
  SetPasswordPage,
  UserManagementLayout,
  UserManagementPage,
  BulkUploadPage,
  ArchivedUsersPage,
  PositionManagementPage,
  CreatePositionPage,
  EditPositionPage,
} from '@tria-plc/iamui-common';
import { ProtectedRoute } from './ProtectedRoute';
import { BackofficeLayout } from '../layouts/BackofficeLayout';
import { AuthLayout } from '../layouts/AuthLayout';
import { DashboardPage } from '../features/dashboard/pages/DashboardPage';
import { ItemPage } from '../features/item/pages/ItemPage';
import { AuditLogPageWrapper } from '../iam/pages/AuditLogPage';
import { IamProviders, AuthProviders } from '../iam/IamProviders';

const router = createBrowserRouter([
  {
    element: (
      <AuthProviders>
        <ProtectedRoute />
      </AuthProviders>
    ),
    children: [
      {
        element: <BackofficeLayout />,
        children: [
          { path: '/', element: <Navigate to="/dashboard" replace /> },
          { path: '/dashboard', element: <DashboardPage /> },
          { path: '/items', element: <ItemPage /> },
          {
            path: '/user-management',
            element: (
              <IamProviders>
                <UserManagementLayout />
              </IamProviders>
            ),
            children: [
              { index: true, element: <UserManagementPage /> },
              { path: 'bulk-upload', element: <BulkUploadPage /> },
              { path: 'archived-users', element: <ArchivedUsersPage /> },
              { path: 'position-management', element: <PositionManagementPage /> },
              { path: 'position-management/new', element: <CreatePositionPage /> },
              { path: 'position-management/edit/:id', element: <EditPositionPage /> },
            ],
          },
          { path: '/audit-log', element: <AuditLogPageWrapper /> },
        ],
      },
    ],
  },
  {
    element: (
      <AuthProviders>
        <AuthLayout />
      </AuthProviders>
    ),
    children: [
      { path: '/login', element: <Login /> },
      { path: '/set-password', element: <SetPasswordPage /> },
    ],
  },
  { path: '/404', element: <div>Page not found</div> },
  { path: '*', element: <Navigate to="/404" replace /> },
]);

export function AppRouter() {
  return <RouterProvider router={router} />;
}
