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 DashboardLayout from '@/layouts/dashboard'
import PageError from '@/pages/sys/error/PageError'
import Login from '@/pages/sys/login/Login'
import { SetupNavigation } from './components/SetupNavigation'

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() {
  const permissionRoutes = usePermissionRoutes()

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

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

  const router = createHashRouter(routes)

  return <RouterProvider router={router} />
}
