import React, { useEffect, useState } from 'react'
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'
import TagPage from '@/pages/TagPage'
import TopNav from '@/components/TopNav'
import TagSidebar from '@/components/TagSidebar'
import TagDetailSidebar from '@/components/TagDetailSidebar'
import PostPage from '@/pages/PostPage'
import PostNewPage from '@/pages/PostNewPage'
import PostDetailPage from '@/pages/PostDetailPage'
import WikiNewPage from '@/pages/WikiNewPage'
import WikiEditPage from '@/pages/WikiEditPage'
import WikiDetailPage from '@/pages/WikiDetailPage'
import { API_BASE_URL } from '@/config'
import axios from 'axios'
import { Toaster } from '@/components/ui/toaster'
import { camelizeKeys } from 'humps'

import type { Post, Tag, User } from '@/types'


export default () => {
  const [user, setUser] = useState<User | null> (null)

  useEffect (() => {
    const createUser = () => (
        axios.post (`${ API_BASE_URL }/users`)
        .then (res => {
          if (res.data.code)
            {
              localStorage.setItem ('user_code', res.data.code)
              setUser (camelizeKeys (res.data.user))
            }
        }))

    const code = localStorage.getItem ('user_code')
    if (code)
      {
        void (axios.post (`${ API_BASE_URL }/users/verify`, { code })
              .then (res => {
                if (res.data.valid)
                  setUser (camelizeKeys (res.data.user))
                else
                  createUser ()
              }))
      }
    else
      createUser ()

    alert ('このサイトはまだ作りかけです!!!!\n出てけ!!!!!!!!!!!!!!!!!!!!')
  }, [])

  return (
      <>
        <Router>
          <div className="flex flex-col h-screen w-screen">
            <TopNav user={user} setUser={setUser} />
            <div className="flex flex-1">
              <Routes>
                <Route path="/" element={<Navigate to="/posts" replace />} />
                <Route path="/posts" element={<PostPage />} />
                <Route path="/posts/new" element={<PostNewPage />} />
                <Route path="/posts/:id" element={<PostDetailPage />} />
                <Route path="/tags/:tag" element={<TagPage />} />
                <Route path="/wiki/:name" element={<WikiDetailPage />} />
                <Route path="/wiki/new" element={<WikiNewPage />} />
                <Route path="/wiki/:id/edit" element={<WikiEditPage />} />
              </Routes>
            </div>
          </div>
        </Router>
        <Toaster />
      </>)
}
