import { useCallback, useEffect, useState } from 'react'
import { getOrgs, type Org } from './api/client'
import LoginPage from './components/LoginPage'
import OrgDetail from './components/OrgDetail'
import OrgList from './components/OrgList'
import SeedUpload from './components/SeedUpload'

// 'checking'이 필요하다. true로 시작하면 첫 렌더에서 getOrgs()가 아직 안 끝났는데도
// 로그인한 것처럼 빈 껍데기를 먼저 보여주고, 401이 온 뒤에야 로그인 화면으로 튄다.
type AuthState = 'checking' | 'authenticated' | 'anonymous'

export default function App() {
  const [orgs, setOrgs] = useState<Org[]>([])
  const [selectedId, setSelectedId] = useState<number | null>(null)
  const [auth, setAuth] = useState<AuthState>('checking')

  const reload = useCallback(async () => {
    try {
      setOrgs(await getOrgs())
      setAuth('authenticated')
    } catch {
      setAuth('anonymous')
    }
  }, [])

  useEffect(() => {
    void reload()
  }, [reload])

  if (auth === 'checking') {
    return <div className="p-8 text-sm text-gray-500">불러오는 중…</div>
  }

  if (auth === 'anonymous') {
    return <LoginPage onSuccess={() => void reload()} />
  }

  const selected = orgs.find((org) => org.id === selectedId) ?? null

  return (
    <div className="flex h-screen">
      <div className="flex w-80 flex-col border-r border-gray-200">
        <OrgList orgs={orgs} selectedId={selectedId} onSelect={setSelectedId} />
        <SeedUpload onUploaded={() => void reload()} />
      </div>

      <main className="flex-1 overflow-y-auto">
        {selected ? (
          <OrgDetail org={selected} onChanged={() => void reload()} />
        ) : (
          <p className="p-8 text-sm text-gray-500">왼쪽에서 기관을 선택하세요.</p>
        )}
      </main>
    </div>
  )
}
