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

/**
 * 로그인 화면. UIWS 2FA 이식 반영:
 *  - 2FA off 응답({ twofa:"false", token }) → 기존처럼 즉시 로그인(회귀 0).
 *  - 2FA on 응답({ twofa:"true", verifyToken, maskedEmail }) → 인증코드 입력 단계로 전환.
 * 색상은 ESN Tailwind 테마 토큰(bg-card/text-brand/border-edge…)만 사용 — 하드코딩 없음.
 */
export default function Login() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError]       = useState('')
  const [loading, setLoading]   = useState(false)
  const [step, setStep]         = useState<'login' | 'verify'>('login')
  const [verifyToken, setVerifyToken] = useState('')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [code, setCode]         = useState('')

  function finishLogin(token: string) {
    localStorage.setItem('esn_token', token)
    localStorage.setItem('esn_user', username)
    navigate('/dashboard')
  }

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError('')
    try {
      const res = await login(username, password)
      const data = res.data?.data
      if (data?.twofa === 'true') {
        setVerifyToken(data.verifyToken)
        setMaskedEmail(data.maskedEmail || '')
        setStep('verify')
      } else {
        if (!data?.token) throw new Error('토큰 없음')
        finishLogin(data.token)
      }
    } catch {
      setError('아이디/비밀번호가 올바르지 않거나 계정이 잠겼습니다.')
    } finally {
      setLoading(false)
    }
  }

  async function handleVerify(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError('')
    try {
      const res = await verify2fa(verifyToken, code)
      finishLogin(res.data?.data?.token)
    } 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">GUARDiA ESN</h1>
          <p className="text-sm text-gray-400 mt-1">
            {step === 'login' ? 'ESL 통합 관리 플랫폼' : '2차 인증'}
          </p>
        </div>

        {step === 'login' ? (
          <form onSubmit={handleLogin} 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>
        ) : (
          <form onSubmit={handleVerify} className="bg-card border border-edge rounded-lg p-6 space-y-4">
            <p className="text-xs text-gray-400">
              {maskedEmail ? `${maskedEmail} 로 발송된 인증코드를 입력하세요.` : '발송된 인증코드를 입력하세요.'}
            </p>
            <div>
              <label className="block text-xs text-gray-400 mb-1">인증코드 6자리</label>
              <input
                inputMode="numeric"
                maxLength={6}
                value={code}
                onChange={e => setCode(e.target.value)}
                placeholder="000000"
                className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white text-center tracking-[0.4em] 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>
            <button
              type="button"
              onClick={() => { setStep('login'); setCode(''); setError('') }}
              className="w-full border border-edge text-gray-400 hover:text-white py-2 rounded text-sm transition-colors"
            >
              뒤로
            </button>
          </form>
        )}
      </div>
    </div>
  )
}
