import { Navigate, Route, Routes, useNavigate, useSearchParams } from 'react-router-dom'
import './App.css'
import { useEffect, useState } from 'react'
import PayPage from './pages/PayPage.tsx'
import PayResultPage from './pages/PayResultPage.tsx'
import Twins from './pages/Twins.tsx'
import PlaceholderPage from './components/PlaceholderPage.tsx'
import { getConfig, getPackage } from './api/user.ts'
import { TEMP_TOKEN_STORAGE_KEY, TOKEN_STORAGE_KEY } from './utils/request.ts'

// http://localhost:5173?token=c3f52a99-c519-427a-af05-364c5f3e59cc
function App() {
  const [isConfigReady, setIsConfigReady] = useState(false)
  const [packageLink, setPackageLink] = useState('')
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const [initialToken] = useState(() => searchParams.get('token'))

  useEffect(() => {
    let isMounted = true

    async function initConfig() {
      if (initialToken) {
        window.sessionStorage.setItem(TOKEN_STORAGE_KEY, initialToken)
      } else if (!window.sessionStorage.getItem(TOKEN_STORAGE_KEY)) {
        navigate('/twins', { replace: true })
      }

      const { data: config } = await getConfig()

      if (config.token) {
        window.sessionStorage.setItem(TEMP_TOKEN_STORAGE_KEY, config.token)
      }

      const { data: packageInfo } = await getPackage()

      if (isMounted) {
        setPackageLink(typeof packageInfo.link === 'string' ? packageInfo.link : '')
        setIsConfigReady(true)
      }
    }

    initConfig()

    return () => {
      isMounted = false
    }
  }, [initialToken, navigate])

  if (!isConfigReady) {
    return null;
  }

  return (
    <Routes>
      <Route path="/" element={<Navigate to="/twins" replace />} />
      <Route path="/pay" element={<PayPage />} />
      <Route path="/pay-result" element={<PayResultPage />} />
      <Route path="/twins" element={<Twins installUrl={packageLink} />} />
      <Route
        path="/404"
        element={<PlaceholderPage path="/404" title="404" description="页面不存在" />}
      />
      <Route path="*" element={<Navigate to="/twins" replace />} />
    </Routes>
  )
}

export default App
