import { useState, FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../hooks/useAuth'

export default function Login() {
  const { login } = useAuth()
  const nav = useNavigate()
  const [form, setForm] = useState({ username: '', password: '' })
  const [err, setErr]   = useState('')
  const [loading, setLoading] = useState(false)

  const submit = async (e: FormEvent) => {
    e.preventDefault(); setErr(''); setLoading(true)
    try {
      await login(form.username, form.password)
      nav('/', { replace: true })
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } }).response?.data?.detail
      setErr(msg ?? '아이디 또는 비밀번호가 올바르지 않습니다.')
    } finally { setLoading(false) }
  }

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'linear-gradient(135deg, #1a1d2e 0%, #2a2d4e 100%)',
    }}>
      <div style={{
        background: '#fff', borderRadius: 14, padding: '44px 40px',
        width: 360, boxShadow: '0 20px 60px rgba(0,0,0,.3)',
      }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>🛡️</div>
          <h1 style={{ fontSize: 22, fontWeight: 800, color: '#1a3a6b', margin: 0 }}>GUARDiA Manager</h1>
          <p style={{ color: '#94a3b8', fontSize: 12, marginTop: 6 }}>
            GUARDiA ITSM 통합 관리자 포털
          </p>
        </div>

        {err && (
          <div style={{ background: '#fff1f2', color: '#dc2626', border: '1px solid #fecaca',
            borderRadius: 7, padding: '10px 14px', fontSize: 13, marginBottom: 16 }}>
            ⚠ {err}
          </div>
        )}

        <form onSubmit={submit}>
          {(['username', 'password'] as const).map(k => (
            <div key={k} style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600,
                color: '#64748b', marginBottom: 6 }}>
                {k === 'username' ? '아이디' : '비밀번호'}
              </label>
              <input type={k === 'password' ? 'password' : 'text'}
                value={form[k]}
                onChange={e => setForm(p => ({ ...p, [k]: e.target.value }))}
                required
                style={{
                  width: '100%', padding: '11px 14px', border: '1.5px solid #e2e8f0',
                  borderRadius: 8, fontSize: 14, outline: 'none', boxSizing: 'border-box',
                }}
                onFocus={e => { e.target.style.borderColor = '#4f6ef7' }}
                onBlur={e => { e.target.style.borderColor = '#e2e8f0' }}
              />
            </div>
          ))}
          <button type="submit" disabled={loading} style={{
            width: '100%', padding: 13, background: '#1a3a6b', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 600,
            cursor: 'pointer', marginTop: 8, opacity: loading ? .7 : 1,
          }}>
            {loading ? '로그인 중...' : '로그인'}
          </button>
        </form>

        <div style={{ marginTop: 20, fontSize: 11, color: '#94a3b8', textAlign: 'center' }}>
          GUARDiA ITSM 계정으로 로그인합니다
        </div>
      </div>
    </div>
  )
}
