import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { login, verify2fa } from '../api/client'
import { Icon } from '../lib/icons'

// GUARDiA Signage 로그인. 2FA off → { twofa:"false", token }. 2FA on → { twofa:"true", verifyToken, maskedEmail }.
export default function Login() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [step, setStep] = useState<'login' | 'verify'>('login')
  const [verifyToken, setVerifyToken] = useState('')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [code, setCode] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  function finish(token: string) {
    localStorage.setItem('sgn_token', token)
    localStorage.setItem('sgn_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('no token')
        finish(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)
      const token = res.data?.data?.token
      if (!token) throw new Error('no token')
      finish(token)
    } catch {
      setError('인증코드가 올바르지 않습니다.')
    } finally { setLoading(false) }
  }

  return (
    <div className="min-h-screen bg-ink flex items-center justify-center p-4">
      <div className="w-full max-w-sm">
        <div className="flex items-center justify-center gap-2 mb-8">
          <Icon name="signboard" size={28} className="text-brand" />
          <div>
            <div className="text-white font-bold text-lg leading-tight">GUARDiA Signage</div>
            <div className="text-gray-400 text-xs">전자간판 중앙관제 플랫폼</div>
          </div>
        </div>

        <div className="bg-card border border-edge rounded-xl p-6">
          {step === 'login' ? (
            <form onSubmit={handleLogin} className="space-y-4">
              <div>
                <label className="block text-xs text-gray-400 mb-1">아이디</label>
                <input value={username} onChange={e => setUsername(e.target.value)} autoFocus
                  className="w-full bg-ink border border-edge rounded px-3 py-2 text-sm text-white outline-none focus:border-brand" />
              </div>
              <div>
                <label className="block text-xs text-gray-400 mb-1">비밀번호</label>
                <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                  className="w-full bg-ink border border-edge rounded px-3 py-2 text-sm text-white outline-none focus:border-brand" />
              </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 disabled:opacity-50">
                {loading ? '로그인 중...' : '로그인'}
              </button>
            </form>
          ) : (
            <form onSubmit={handleVerify} className="space-y-4">
              <p className="text-sm text-gray-300">2차 인증 코드를 입력하세요.</p>
              {maskedEmail && <p className="text-xs text-gray-500">{maskedEmail} 로 전송됨</p>}
              <input value={code} onChange={e => setCode(e.target.value)} autoFocus placeholder="인증코드"
                className="w-full bg-ink border border-edge rounded px-3 py-2 text-sm text-white tracking-widest outline-none focus:border-brand" />
              {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 disabled:opacity-50">
                {loading ? '확인 중...' : '인증 확인'}
              </button>
              <button type="button" onClick={() => { setStep('login'); setError('') }}
                className="w-full text-gray-400 hover:text-white text-xs">← 돌아가기</button>
            </form>
          )}
        </div>
        <p className="text-center text-gray-600 text-xs mt-6">© GUARDiA · e-SignBoard 중앙관제</p>
      </div>
    </div>
  )
}
