import { useEffect } from 'react'
import { useRoute, useRouter } from 'react-router5'
import { type Route, type Router, createRouter } from 'router5'
import browserPlugin from 'router5-plugin-browser'

const routes: Route[] = [
  {
    name: 'home',
    path: '/',
  },
  {
    name: 'sections',
    path: '/:section',
  },
  {
    name: 'components',
    path: '/:section/:component',
  },
  {
    name: 'views',
    path: '/:section/:component/:block/:state/:view',
  },
]

export const createAppRouter = (): Router => {
  const router = createRouter(routes, {
    allowNotFound: true,
    trailingSlashMode: 'never',
  })

  router.usePlugin(browserPlugin())

  return router
}

export const useTypedRoute = (): Based.UI.Playground.TypedRoute => {
  const { route } = useRoute()

  if (!route)
    return {
      name: '',
      params: {
        section: 'components',
        component: '',
        block: '',
        state: 'preview',
        view: 'compact',
      },
    }

  return {
    name: route.name,
    params: route.params,
  } as Based.UI.Playground.TypedRoute
}

export const Redirect = ({
  to,
  section,
  component,
  block,
  state,
  view,
}: Based.UI.Playground.RedirectProps) => {
  const router = useRouter()

  useEffect(() => {
    if (router) {
      const params = {
        ...(section && { section }),
        ...(component && { component }),
        ...(block && { block }),
        ...(state && { state }),
        ...(view && { view }),
      }

      router.navigate(to, params)
    }
  }, [router, to, section, component, block, state, view])

  return null
}
