// React
import React, { FC, useEffect } from 'react'
import { Route, Routes, useLocation } from 'react-router'

// Redux
import { useSelector, useDispatch } from 'react-redux'
import { actionCreators as settingsActionCreators } from './store/reducers/Content'

// Components
import { DynamicLayout } from './layouts'
import { DynamicPage } from './pages'
import { IRouteModel } from './models'
import { ApplicationState } from './store'


interface IRouteProp {
  path: string,
  element?: JSX.Element
}

const NestedRoutes = (routes: IRouteModel[], tag: string | undefined = undefined) => {
  if(!Array.isArray(routes)) return

  return routes.map((route: IRouteModel, index: number) => {
    const routeProps: IRouteProp = {
      path: route.target
    }

    if (route.component) {
      const page = <DynamicPage tag={route.component} />
      routeProps.element = tag ? <DynamicLayout tag={tag}>{page}</DynamicLayout> : page
    }

    

    return <Route key={index} { ...routeProps }>{Array.isArray(route.childRoutes) ? NestedRoutes(route.childRoutes, tag) : ''}</Route>
  })
}

const App: FC = () => {
  const { pathname } = useLocation()
  const dispatch = useDispatch()
  const state =  useSelector((state: ApplicationState) => state.content)

  useEffect(() => {
    dispatch(settingsActionCreators.requestContent())
  }, [])

  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    })
  }, [pathname])

  return <>
    <Routes>
      {state?.routes ? NestedRoutes(state.routes,  'PublicLayout') : ''}
      {state?.adminRoutes ? NestedRoutes(state.adminRoutes,  'AdminLayout') : ''}
      {state?.serviceRoutes ? NestedRoutes(state.serviceRoutes) : ''}
    </Routes>
  </>
}

export {
  App
}
