import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { login, getMe } from '../api/client'
import { verify2fa } from '../api/uiws'
import AuthHelperModals, { type AuthHelperKind } from './AuthHelperModals'

/**
 * CMS 로그인 — UIWS 2FA 레이어 대응.
 * - 1차: /api/cms/auth/login → 2FA off 면 { token } 즉시 발급(회귀 0),
 *        2FA on 이면 { verifyToken, step, maskedEmail } → 2차 코드 입력 단계로 전환.
 * - 2차: /api/cms/auth/verify (verifyToken + code) → access 토큰 발급.
 * 인증코드는 서버 메일/로그 채널로만 전달(응답·화면에 코드 노출 없음).
 */
export default function Login() {
  const [step, setStep] = useState<'login' | 'verify'>('login')
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [code, setCode] = useState('')
  const [verifyToken, setVerifyToken] = useState('')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [err, setErr] = useState('')
  const [busy, setBusy] = useState(false)
  const [helper, setHelper] = useState<AuthHelperKind | null>(null)
  const nav = useNavigate()

  // 토큰 저장 + 역할 선조회 후 대시보드 진입(공통)
  const finishLogin = async (token: string) => {
    localStorage.setItem('cms_token', token)
    try {
      const me = await getMe()
      const d = me.data?.data || {}
      if (d.role) localStorage.setItem('cms_role', d.role)
      if (d.username) localStorage.setItem('cms_user', d.username)
    } catch { /* noop */ }
    nav('/dashboard')
  }

  const submitLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr(''); setBusy(true)
    try {
      const res = await login(username, password)
      const d = res.data?.data || {}
      if (d.twofa === 'true') {
        // 2FA on — 2차 코드 입력 단계로
        setVerifyToken(d.verifyToken || '')
        setMaskedEmail(d.maskedEmail || '')
        setStep('verify')
      } else {
        // 2FA off(또는 미설정) — 기존 단일 로그인 흐름
        const token = d.token
        if (!token) throw new Error('no token')
        await finishLogin(token)
      }
    } catch {
      setErr('로그인 실패 — 아이디/비밀번호를 확인하세요.')
    } finally {
      setBusy(false)
    }
  }

  const submitVerify = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr(''); setBusy(true)
    try {
      const res = await verify2fa(verifyToken, code.trim())
      const token = res.data?.data?.token
      if (!token) throw new Error('no token')
      await finishLogin(token)
    } catch {
      setErr('인증 실패 — 코드가 올바르지 않거나 만료되었습니다.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-ink">
      <form onSubmit={step === 'login' ? submitLogin : submitVerify}
        className="w-[360px] bg-panel border border-edge rounded-2xl p-8">
        <div className="flex items-center gap-2 justify-center mb-6">
          <img src="/login.png" alt="GUARDiA" style={{ height: 36, width: 'auto' }}
            onError={e => { (e.target as HTMLImageElement).style.display = 'none' }} />
          <span className="text-xl font-bold">GUARDiA CMS</span>
        </div>
        <p className="text-center text-sm text-slate-400 mb-6">AI 콘텐츠 관리 시스템</p>

        {step === 'login' ? (
          <>
            <label className="block text-xs text-slate-400 mb-1">아이디</label>
            <input value={username} onChange={e => setUsername(e.target.value)}
              className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
            <label className="block text-xs text-slate-400 mb-1">비밀번호</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)}
              className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
            {err && <p className="text-rose-400 text-xs mb-3">{err}</p>}
            <button disabled={busy} className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90 disabled:opacity-60">
              {busy ? '로그인 중…' : '로그인'}
            </button>
            <p className="text-center text-[11px] text-slate-500 mt-4">admin / editor / author · admin123</p>
            {/* 로그인 보조 3링크(UIWS auth 패턴 이식) */}
            <div className="flex items-center justify-center gap-2 text-[11px] text-slate-400 mt-3">
              <button type="button" onClick={() => setHelper('signup')} className="hover:text-brand">회원가입</button>
              <span className="text-slate-600">|</span>
              <button type="button" onClick={() => setHelper('findId')} className="hover:text-brand">아이디 찾기</button>
              <span className="text-slate-600">|</span>
              <button type="button" onClick={() => setHelper('reset')} className="hover:text-brand">비밀번호 초기화</button>
            </div>
          </>
        ) : (
          <>
            <p className="text-center text-xs text-slate-400 mb-4">
              2차 인증 코드를 입력하세요{maskedEmail ? ` (${maskedEmail} 발송)` : ''}.
            </p>
            <label className="block text-xs text-slate-400 mb-1">인증 코드</label>
            <input value={code} onChange={e => setCode(e.target.value)} inputMode="numeric"
              maxLength={6} autoFocus placeholder="6자리 코드"
              className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm tracking-[0.3em] text-center focus:border-brand outline-none" />
            {err && <p className="text-rose-400 text-xs mb-3">{err}</p>}
            <button disabled={busy} className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90 disabled:opacity-60">
              {busy ? '확인 중…' : '인증 확인'}
            </button>
            <button type="button" onClick={() => { setStep('login'); setCode(''); setErr('') }}
              className="w-full py-2 mt-2 rounded-lg text-slate-400 text-xs hover:text-slate-200">
              ← 로그인으로 돌아가기
            </button>
          </>
        )}
      </form>
      <AuthHelperModals kind={helper} onClose={() => setHelper(null)} />
    </div>
  )
}
