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

export default function App() {
  const [orgs, setOrgs] = useState<Org[]>([])
  const [selectedId, setSelectedId] = useState<number | null>(null)
  const [authenticated, setAuthenticated] = useState(true)

  const reload = useCallback(async () => {
    try {
      setOrgs(await getOrgs())
      setAuthenticated(true)
    } catch {
      setAuthenticated(false)
    }
  }, [])

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

  if (!authenticated) {
    return <LoginPage onSuccess={() => void reload()} />
  }

  return (
    <div className="flex h-screen">
      <OrgList orgs={orgs} selectedId={selectedId} onSelect={setSelectedId} />
      <main className="flex-1 overflow-y-auto p-8">
        <h1 className="text-lg font-semibold">기관관리</h1>
        <p className="mt-2 text-sm text-gray-500">기관 {orgs.length}개</p>
      </main>
    </div>
  )
}
