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/Settings'

// Components
import { DynamicLayout } from './layouts'
import { DynamicPage } from './pages'
import { IReduxState, IRoute } from './interfaces'

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

const NestedRoutes = (routes: IRoute[], tag: string | undefined = undefined) => {

  if(!Array.isArray(routes)) return

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

    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 { routes, adminRoutes, serviceRoutes } = useSelector((state: IReduxState) => state.settings)

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

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

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

export {
  App
}
