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

/**
 * CMS 로그인 — UIWS 2FA 레이어 + Authenticator(OTP) 확장.
 * 1단계: 아이디/비밀번호 → /api/cms/auth/login.
 *   - twofa="false": 즉시 { token } 발급(기존 단일 로그인 회귀 0).
 *   - twofa="true": verifyMethod 로 2차 분기.
 *       · OTP        : Authenticator 6자리 → /verify-otp
 *       · OTP_SETUP  : QR(qrImage)+수동키(secret) 등록 후 6자리 → /verify-otp
 *       · EMAIL(기타): 이메일 인증코드 6자리 → /verify (하위호환)
 * 2단계: verify-token + 코드 → access 발급 → getMe 로 역할 저장 → /dashboard.
 * 보안: OTP secret/QR·인증코드는 화면 표시용만 — 로그/저장 절대 금지.
 */
type VerifyMethod = 'OTP' | 'OTP_SETUP' | 'EMAIL'

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 [verifyMethod, setVerifyMethod] = useState<VerifyMethod>('EMAIL')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [qrImage, setQrImage] = useState('')   // OTP_SETUP 등록 순간만 존재
  const [secret, setSecret] = useState('')     // OTP_SETUP 등록 순간만 존재
  const [err, setErr] = useState('')
  const [busy, setBusy] = useState(false)
  const [helper, setHelper] = useState<AuthHelperKind | null>(null)
  const nav = useNavigate()

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

  // 토큰 저장 + 역할 선조회 후 대시보드 진입(공통)
  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') {
        setVerifyToken(d.verifyToken || '')
        setVerifyMethod((d.verifyMethod as VerifyMethod) || 'EMAIL')
        setMaskedEmail(d.maskedEmail || '')
        setQrImage(d.qrImage || '')
        setSecret(d.secret || '')
        setCode('')
        setStep('verify')
      } else {
        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 {
      // OTP·OTP_SETUP 은 /verify-otp, 이메일은 /verify(하위호환)
      const res = isOtp
        ? await verifyOtp(verifyToken, code.trim())
        : 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)
    }
  }

  const backToLogin = () => {
    setStep('login'); setCode(''); setErr('')
    setQrImage(''); setSecret('')  // 시크릿 잔존 방지
  }

  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>

        {step === 'login' ? (
          <>
            <p className="text-center text-sm text-slate-400 mb-6">AI 콘텐츠 관리 시스템</p>
            <label className="block text-xs text-slate-400 mb-1">아이디</label>
            <input value={username} onChange={e => setUsername(e.target.value)} autoComplete="username"
              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)} autoComplete="current-password"
              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>
          </>
        ) : (
          <>
            <div className="flex items-center gap-2 justify-center mb-4">
              <ShieldCheck size={20} className="text-brand" />
              <span className="text-lg font-bold">2차 인증</span>
            </div>

            {isOtp ? (
              isSetup ? (
                <>
                  <p className="text-center text-sm text-slate-400 mb-3">
                    최초 로그인입니다. 아래 QR을 Authenticator 앱(Google·Microsoft)으로 스캔해
                    등록한 뒤 6자리 코드를 입력하세요.
                  </p>
                  {qrImage && (
                    <div className="flex justify-center mb-3">
                      <img src={qrImage} alt="OTP QR" width={180} height={180}
                        style={{ background: '#fff', padding: 8, borderRadius: 8 }} />
                    </div>
                  )}
                  {secret && (
                    <div className="mb-4">
                      <div className="text-[11px] text-slate-500 mb-1">QR 스캔이 안 되면 수동 입력 키</div>
                      <code className="block text-xs text-accent bg-ink border border-edge rounded-md px-2 py-1.5 break-all select-all">
                        {secret}
                      </code>
                    </div>
                  )}
                </>
              ) : (
                <p className="text-center text-sm text-slate-400 mb-6">
                  Authenticator 앱에 표시된 6자리 코드를 입력하세요.
                </p>
              )
            ) : (
              <p className="text-center text-xs text-slate-400 mb-4">
                이메일로 발송된 6자리 인증 코드를 입력하세요{maskedEmail ? ` (${maskedEmail})` : ''}.
              </p>
            )}

            <label className="block text-xs text-slate-400 mb-1">인증 코드</label>
            <input value={code} onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
              inputMode="numeric" autoComplete="one-time-code" maxLength={6} autoFocus placeholder="000000"
              className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm tracking-[0.4em] text-center focus:border-brand outline-none" />
            {err && <p className="text-rose-400 text-xs mb-3">{err}</p>}
            <button disabled={busy || code.length !== 6}
              className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90 disabled:opacity-60">
              {busy ? '인증 중…' : isSetup ? '등록하고 로그인' : '인증 확인'}
            </button>
            <button type="button" onClick={backToLogin}
              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>
  )
}
