// src/app/router/router.tsx
import { lazy, Suspense, type ReactNode } from 'react'
import { createBrowserRouter, Navigate } from 'react-router-dom'

import { AppLayout } from '../layouts/AppLayout'

const EmployeesPage = lazy(() =>
  import('../../pages/EmployeesPage/EmployeesPage').then((module) => ({
    default: module.EmployeesPage,
  })),
)

const MachinesPage = lazy(() =>
  import('../../pages/MachinesPage/MachinesPage').then((module) => ({
    default: module.MachinesPage,
  })),
)

const MachinePage = lazy(() =>
  import('../../pages/MachinePage/MachinePage').then((module) => ({
    default: module.MachinePage,
  })),
)

function lazyRoute(element: ReactNode) {
  return <Suspense fallback={null}>{element}</Suspense>
}

export const router = createBrowserRouter([
  {
    path: '/',
    element: <AppLayout />,
    children: [
      {
        index: true,
        element: <Navigate to="/machines" replace />,
      },
      {
        path: 'users',
        element: lazyRoute(<EmployeesPage />),
      },
      {
        path: 'machines',
        element: lazyRoute(<MachinesPage />),
      },
      {
        path: 'machines/:machineId',
        element: lazyRoute(<MachinePage />),
      },
      {
        path: 'employees',
        element: <Navigate to="/users" replace />,
      },
      {
        path: 'devices/*',
        element: <Navigate to="/machines" replace />,
      },
      {
        path: 'map',
        element: <Navigate to="/machines" replace />,
      },
      {
        path: '*',
        element: <Navigate to="/machines" replace />,
      },
    ],
  },
])
