// 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 { RouteModel } from './models'
import { ApplicationState } from './store'
import { Loader } from './components/Loader'
import { Helmet } from './components/ReactHelmet'

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

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

  return routes.map((route: RouteModel, 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 = () => {
  const { pathname } = useLocation()
  const dispatch = useDispatch()

  const { content, header, loader } =  useSelector((state: ApplicationState) => state)

  useEffect(() => {
    dispatch(settingsActionCreators.requestContent({ searchParams: { locale: "en-US" }}))
  }, [])

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


  const {
    title = "",
    link = {},
    meta = {}
  } = header ? header : {}

  return <>
    <Helmet>
      <title>{title}</title>
      <meta charSet="utf-8" />
      {Object.keys(link).map((rel, index) => <link key={index} rel={rel} href={link[index]} />)}
      {Object.keys(meta).map((name, index) => <meta key={index} name={name} content={meta[index]} />)}
    </Helmet>

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

    {loader ? <Loader {...loader} /> : ''}
  </>
}

export {
  App
}
