import React from 'react'
import { Route, Navigate } from '@aniyajs/plugin-router'
import type { IRoute } from '@aniyajs/lib/utils'
import { Outlet } from '@aniyajs/plugin-router'

export interface RenderRoutesPropsType {
  route: IRoute
  key: any
}

const renderRoute: React.FC<RenderRoutesPropsType> = ({ route, key }) => {
  if (!route.path) {
    return null
  }

  if (route.redirect) {
    return (
      <Route
        key={key}
        path={route.path}
        element={<Navigate to={route.redirect} replace />}
      />
    )
  }

  if (!route.component) {
    return null
  }

  if (route.children && route.children?.length > 0) {
    return (
      <Route
        key={key}
        path={route.path}
        element={
          <route.component>
            <Outlet />
          </route.component>
        }
      >
        {route.children?.map((item, i) => renderRoute({ route: item, key: i }))}
      </Route>
    )
  }

  return <Route key={key} path={route.path} element={<route.component />} />
}

export default renderRoute
