import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { ShieldCheck } from 'lucide-react'
import { login } from '../api/client'
import { verify2fa, verifyOtp } from '../api/uiws'

/**
 * 로그인 화면. UIWS(UIMS) 2FA 이식 + Authenticator(OTP) 확장 반영:
 *  - 2FA off 응답({ twofa:"false", token }) → 기존처럼 즉시 로그인(회귀 0).
 *  - 2FA on 응답 → verifyMethod 로 2차 분기.
 *      · OTP        : Authenticator 6자리 → /verify-otp
 *      · OTP_SETUP  : QR(qrImage)+수동키(secret) 등록 후 6자리 → /verify-otp
 *      · EMAIL(기타): 이메일 인증코드(step=EMAIL) 6자리 → /verify (하위호환)
 *  - 하단 로그인 보조 3종(회원가입·아이디찾기·비밀번호 초기화) 링크.
 * 색상은 ESN Tailwind 테마 토큰(bg-card/text-brand/border-edge…)만 사용 — 하드코딩 없음.
 * 보안: OTP secret/QR·인증코드는 화면 표시용만 — 로그/저장 절대 금지.
 */
type VerifyMethod = 'OTP' | 'OTP_SETUP' | 'EMAIL'

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 [verifyMethod, setVerifyMethod] = useState<VerifyMethod>('EMAIL')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [qrImage, setQrImage]   = useState('')   // OTP_SETUP 등록 순간만 존재
  const [secret, setSecret]     = useState('')   // OTP_SETUP 등록 순간만 존재
  const [code, setCode]         = useState('')

  const isOtp = verifyMethod === 'OTP' || verifyMethod === 'OTP_SETUP'
  const isSetup = verifyMethod === 'OTP_SETUP'

  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)
        // OTP 경로는 verifyMethod(OTP|OTP_SETUP), 이메일 경로는 step=EMAIL(=verifyMethod 미지정).
        setVerifyMethod((data.verifyMethod as VerifyMethod) || 'EMAIL')
        setMaskedEmail(data.maskedEmail || '')
        setQrImage(data.qrImage || '')
        setSecret(data.secret || '')
        setCode('')
        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 {
      // OTP·OTP_SETUP 은 /verify-otp, 이메일은 /verify(하위호환)
      const res = isOtp
        ? await verifyOtp(verifyToken, code)
        : await verify2fa(verifyToken, code)
      const token = res.data?.data?.token
      if (!token) throw new Error('토큰 없음')
      finishLogin(token)
    } catch {
      setError('인증 코드가 올바르지 않거나 만료되었습니다.')
    } finally {
      setLoading(false)
    }
  }

  function backToLogin() {
    setStep('login'); setCode(''); setError('')
    setQrImage(''); setSecret('')  // 시크릿 잔존 방지
  }

  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 flex items-center justify-center gap-1.5">
            {step === 'verify' && <ShieldCheck size={15} className="text-brand" />}
            {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>

            {/* 로그인 보조 3종 (UIWS 이식) */}
            <div className="flex items-center justify-center gap-3 pt-1 text-xs text-gray-400">
              <Link to="/signup" className="hover:text-brand transition-colors">회원가입</Link>
              <span className="text-edge">|</span>
              <Link to="/find-id" className="hover:text-brand transition-colors">아이디 찾기</Link>
              <span className="text-edge">|</span>
              <Link to="/reset-pw" className="hover:text-brand transition-colors">비밀번호 초기화</Link>
            </div>
          </form>
        ) : (
          <form onSubmit={handleVerify} className="bg-card border border-edge rounded-lg p-6 space-y-4">
            {isOtp ? (
              isSetup ? (
                <>
                  <p className="text-xs text-gray-400">
                    최초 로그인입니다. 아래 QR을 Authenticator 앱(Google·Microsoft)으로 스캔해
                    등록한 뒤 6자리 코드를 입력하세요.
                  </p>
                  {qrImage && (
                    <div className="flex justify-center">
                      <img src={qrImage} alt="OTP QR" width={176} height={176}
                        style={{ background: '#fff', padding: 8, borderRadius: 8 }} />
                    </div>
                  )}
                  {secret && (
                    <div>
                      <div className="text-[11px] text-gray-500 mb-1">QR 스캔이 안 되면 수동 입력 키</div>
                      <code className="block text-xs text-accent bg-panel border border-edge rounded px-2 py-1.5 break-all select-all">
                        {secret}
                      </code>
                    </div>
                  )}
                </>
              ) : (
                <p className="text-xs text-gray-400">
                  Authenticator 앱에 표시된 6자리 코드를 입력하세요.
                </p>
              )
            ) : (
              <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"
                autoComplete="one-time-code"
                maxLength={6}
                value={code}
                onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="000000"
                autoFocus
                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 || code.length !== 6}
              className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm font-medium transition-colors disabled:opacity-50"
            >
              {loading ? '인증 중...' : isSetup ? '등록하고 로그인' : '인증하고 로그인'}
            </button>
            <button
              type="button"
              onClick={backToLogin}
              className="w-full border border-edge text-gray-400 hover:text-white py-2 rounded text-sm transition-colors"
            >
              뒤로
            </button>
          </form>
        )}
      </div>
    </div>
  )
}
