import { ErrorBoundary } from 'react-error-boundary'
import { createHashRouter, Navigate, type RouteObject } from 'react-router'
import { RouterProvider } from 'react-router/dom'
import type { AppRouteObject } from '#/router'
import ProtectedRoute from '@/router/components/protected-route'
import { usePermissionRoutes } from '@/router/hooks'
import { ERROR_ROUTE } from '@/router/routes/error-routes'
// import HOME_ROUTE from '@/router/routes/modules/constantRoutes'
import DashboardLayout from '@/layouts/dashboard'
import PageError from '@/pages/sys/error/PageError'
import Login from '@/pages/sys/login/Login'

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env

const PUBLIC_ROUTE: AppRouteObject = {
  path: '/login',
  element: (
    <ErrorBoundary FallbackComponent={PageError}>
      <Login />
    </ErrorBoundary>
  )
}

const NO_MATCHED_ROUTE: AppRouteObject = {
  path: '*',
  element: <Navigate to='/404' replace />
}

export default function Router() {
  console.log('Router render')
  const permissionRoutes = usePermissionRoutes()

  // 动态路由
  const PROTECTED_ROUTE: AppRouteObject = {
    path: '/',
    element: (
      <ProtectedRoute>
        <DashboardLayout />
      </ProtectedRoute>
    ),
    children: [
      { index: true, element: <Navigate to={HOMEPAGE} replace /> },
      // HOME_ROUTE,
      ...permissionRoutes
    ]
  }

  const routes = [PUBLIC_ROUTE, PROTECTED_ROUTE, ERROR_ROUTE, NO_MATCHED_ROUTE] as RouteObject[]
  console.log(routes)

  const router = createHashRouter(routes)
  console.log(router)

  return <RouterProvider router={router} />
}
