import { useState } from 'react'
import { Routes, Route, Navigate, Outlet, useLocation } from 'react-router-dom'
import { useAuth } from '../../auth'
import BirthdayPage from '../BirthdayPage'
import BirthtimePage from '../BirthtimePage'
import CreateProfilePage from '../CreateProfilePage'
import EmailEnterPage from '../EmailEnterPage'
import SubscriptionPage from '../SubscriptionPage'
import PaymentPage from '../PaymentPage'
import WallpaperPage from '../WallpaperPage'
import NotFoundPage from '../NotFoundPage'
import Header from '../Header'
import Navbar from '../Navbar'
import Footer from '../Footer'
import routes, { hasNavigation } from '../../routes'
import './styles.css'

function App(): JSX.Element {
  return (
    <Routes>
      <Route element={<Layout />}>
        <Route path={routes.client.root()} element={
          <Navigate to={routes.client.birthday()} />
        } />
        <Route path={routes.client.birthday()} element={<BirthdayPage />} />
        <Route path={routes.client.birthtime()} element={<BirthtimePage />} />
        <Route path={routes.client.createProfile()} element={<SkipStep />} />
        <Route path={routes.client.emailEnter()} element={<EmailEnterPage />} />
        <Route element={<PrivateOutlet />}>
          <Route path={routes.client.subscription()} element={<SubscriptionPage />} />
          <Route path={routes.client.paymentMethod()} element={<PaymentPage />} />
          <Route path={routes.client.wallpaper()} element={<WallpaperPage />} />
        </Route>
        <Route path="*" element={<NotFoundPage />} />
      </Route>
    </Routes>
  )
}

function Layout(): JSX.Element {
  const location = useLocation()
  const showNavbar = hasNavigation(location.pathname)
  const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false)
  return (
    <div className='container'>
      <Header openMenu={() => setIsMenuOpen(true)}/>
      <main className='content'><Outlet /></main>
      <Footer color={showNavbar ? 'black' : 'white'}/>
      { showNavbar ? <Navbar isOpen={isMenuOpen} closeMenu={() => setIsMenuOpen(false)} /> : null}
    </div>
  )
}

function PrivateOutlet(): JSX.Element {
  const { user } = useAuth()
  return user ? <Outlet /> : <Navigate to={routes.client.root()} replace={true} />
}

function SkipStep(): JSX.Element {
  const { user } = useAuth()
  return user ? <Navigate to={routes.client.emailEnter()} replace={true} /> : <CreateProfilePage />
}

export default App
