import { lazy, Suspense } from 'react'
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 { loadComponentFromPath } from './hooks/use-permission-routes'
import PageError from '@/pages/sys/error/PageError'
import Login from '@/pages/sys/login/Login'
import { CircleLoading } from '@/components/loading'

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()
  console.log(permissionRoutes)
  // console.log(HOMEPAGE)

  const HOMEPAGEElement = lazy(loadComponentFromPath('/dashboard/index') as any)
  const HOMEPAGE_ROUTE = {
    path: '/dashboard/index',
    element: (
      <Suspense fallback={<CircleLoading />}>
        <HOMEPAGEElement />
      </Suspense>
    ),
    order: 0,
    meta: {}
  } as AppRouteObject
  // 动态路由
  const PROTECTED_ROUTE: AppRouteObject = {
    path: '/',
    element: (
      <ProtectedRoute>
        <DashboardLayout />
      </ProtectedRoute>
    ),
    children: [
      { index: true, element: <Navigate to={'/system//auth/user/index'} replace /> },
      ...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} />
}
