import { useEffect, useState } from 'react'
import { Link, Route, Routes } from 'react-router-dom'
import { api } from './api'
import AlbumsPage from './pages/AlbumsPage'
import AlbumPage from './pages/AlbumPage'
import SharePage from './pages/SharePage'

function AdminLayout({ children }) {
  const [me, setMe] = useState(undefined) // undefined=loading, null=logged out

  useEffect(() => {
    api('/api/me')
      .then(setMe)
      .catch(() => setMe(null))
  }, [])

  if (me === undefined) return <div className="center-page">Loading…</div>
  if (me === null) {
    const authError = new URLSearchParams(window.location.search).get('auth_error')
    return (
      <div className="center-page">
        <div className="login-card">
          <h1>Photos</h1>
          <p>Photographer sign-in</p>
          <a className="btn btn-primary" href="/api/auth/login">
            Sign in
          </a>
          {authError && <p className="error">{authError}</p>}
        </div>
      </div>
    )
  }

  return (
    <>
      <header className="topbar">
        <Link to="/" className="brand">
          Photos
        </Link>
        <span className="topbar-right">
          <span className="muted">{me.email}</span>
          <button
            className="btn btn-ghost"
            onClick={async () => {
              await api('/api/auth/logout', { method: 'POST' })
              setMe(null)
            }}
          >
            Sign out
          </button>
        </span>
      </header>
      <main className="page">{children}</main>
    </>
  )
}

export default function App() {
  return (
    <Routes>
      <Route path="/s/:token" element={<SharePage />} />
      <Route
        path="/"
        element={
          <AdminLayout>
            <AlbumsPage />
          </AdminLayout>
        }
      />
      <Route
        path="/albums/:id"
        element={
          <AdminLayout>
            <AlbumPage />
          </AdminLayout>
        }
      />
      <Route path="*" element={<div className="center-page">Not found</div>} />
    </Routes>
  )
}
