import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { login } from '../api/client'

export default function Login() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError]       = useState('')
  const [loading, setLoading]   = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError('')
    try {
      const res = await login(username, password)
      const token = res.data?.data?.token
      if (!token) throw new Error('토큰 없음')
      localStorage.setItem('esn_token', token)
      navigate('/dashboard')
    } catch {
      setError('로그인 실패: 아이디/비밀번호를 확인하세요.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-ink flex items-center justify-center">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-brand">zioinfo-esn</h1>
          <p className="text-sm text-gray-400 mt-1">ESL 통합 관리 플랫폼</p>
        </div>
        <form onSubmit={handleSubmit} className="bg-card border border-edge rounded-lg p-6 space-y-4">
          <div>
            <label className="block text-xs text-gray-400 mb-1">아이디</label>
            <input
              value={username}
              onChange={e => setUsername(e.target.value)}
              placeholder="admin"
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-brand focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-xs text-gray-400 mb-1">비밀번호</label>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-brand focus:outline-none"
            />
          </div>
          {error && <p className="text-red-400 text-xs">{error}</p>}
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm font-medium transition-colors disabled:opacity-50"
          >
            {loading ? '로그인 중...' : '로그인'}
          </button>
        </form>
      </div>
    </div>
  )
}
