import { useState } from 'react'
import { login } from '../api/client'

export default function LoginPage({ onSuccess }: { onSuccess: () => void }) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)
    try {
      await login(username, password)
      onSuccess()
    } catch (err) {
      setError((err as Error).message)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50">
      <form onSubmit={submit} className="w-80 rounded-lg border border-gray-200 bg-white p-6">
        <h1 className="text-lg font-semibold">ITN-HUB</h1>
        <p className="mt-1 text-sm text-gray-500">사업관리시스템</p>

        <input
          className="mt-6 w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
          placeholder="아이디"
          aria-label="아이디"
          autoComplete="username"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
        <input
          className="mt-2 w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
          type="password"
          placeholder="비밀번호"
          aria-label="비밀번호"
          autoComplete="current-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />

        {error && <p className="mt-3 text-sm text-red-600">{error}</p>}

        <button
          type="submit"
          className="mt-4 w-full rounded-md bg-blue-600 py-2 text-sm font-medium text-white"
        >
          로그인
        </button>
      </form>
    </div>
  )
}
