import React from 'react'
import {
  Route,
  Redirect,
  Switch,
  useRouteMatch,
} from 'react-router-dom'

import { indexLexics } from 'config/lexics/indexLexics'
import { useLexicsConfig } from 'features/LexicsStore'
import { PAGES } from 'config'
import { devices } from 'config/devices'
import { HomePage } from 'features/HomePage'
import { TeamPage } from 'features/TeamPage'
import { MatchPage } from 'features/MatchPage'
import { PlayerPage } from 'features/PlayerPage'
import { TournamentPage } from 'features/TournamentPage'
import { ExtendedSearchPage } from 'features/ExtendedSearchPage'
import { LanguageSelect } from 'features/LanguageSelect'
import { UserAccount } from 'features/UserAccount'
import { ScoreStore, ToggleScore } from 'features/ToggleScore'
import { MainWrapper } from 'features/MainWrapper'

import { UserFavorites } from 'features/UserFavorites'
import { UserFavoritesStore } from 'features/UserFavorites/store'
import { useMediaQuery } from 'features/MediaQuery'
import { FormStore } from 'features/FormStore'

export const AuthenticatedApp = () => {
  useLexicsConfig(indexLexics)
  const isMobile = useMediaQuery({ query: devices.tablet })
  const isUserAccountPage = useRouteMatch(PAGES.useraccount)?.isExact || false
  const isExtendedSearchPage = useRouteMatch(PAGES.extendedSearch)?.isExact || false

  return (
    <ScoreStore>
      {
        isMobile || isUserAccountPage
          ? null
          : <LanguageSelect />
      }
      {isExtendedSearchPage ? null : <ToggleScore />}
      <Switch>
        <Route path={PAGES.useraccount}>
          <UserAccountForm />
        </Route>
        <UserFavoritesStore>
          <MainWrapper>
            {!isMobile && <UserFavorites />}
            <Route exact path={PAGES.home}>
              <HomePage />
            </Route>

            <Route path={`/:sportName${PAGES.tournament}/:pageId`}>
              <TournamentPage />
            </Route>

            <Route path={`/:sportName${PAGES.team}/:pageId`}>
              <TeamPage />
            </Route>
            <Route path={`/:sportName${PAGES.player}/:pageId`}>
              <PlayerPage />
            </Route>
            <Route path={`/:sportName${PAGES.match}/:pageId`}>
              <MatchPage />
            </Route>
            <Route path={PAGES.extendedSearch}>
              <ExtendedSearchPage />
            </Route>
          </MainWrapper>
        </UserFavoritesStore>
        <Redirect to={PAGES.home} />
      </Switch>
    </ScoreStore>
  )
}

export const UserAccountForm = () => (
  <FormStore>
    <UserAccount />
  </FormStore>
)
