import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { login, getMe } from '../api/client'
import { verify2fa } from '../api/uiws'
import LanguageSwitcher from '../i18n/LanguageSwitcher'

/**
 * 관리자/매장(운영) 로그인.
 * - UIWS 2FA 이식: 운영 계정(ADMIN/MANAGER) + twofa-enabled 시 1차 로그인 후 verify-token + 이메일코드 단계.
 *   응답 { twofa:"false", token } → 즉시 로그인(2FA off 또는 토글 off 회귀 0).
 *   응답 { twofa:"true", verifyToken, maskedEmail } → 코드 입력 화면 → /api/mall/auth/verify → token.
 * - 인증코드는 서버 메일/감사 채널로만 전달(응답 미노출). 메일 미설정(admin 등 email 미시드)은 서버 로그 폴백.
 */
export default function AdminLogin() {
  const { t } = useTranslation()
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [err, setErr] = useState('')
  // 2FA 단계
  const [step, setStep] = useState<'login' | 'verify'>('login')
  const [verifyToken, setVerifyToken] = useState('')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [code, setCode] = useState('')
  const nav = useNavigate()

  useEffect(() => {
    document.documentElement.classList.add('admin-shell')
    return () => document.documentElement.classList.remove('admin-shell')
  }, [])

  /** 토큰 저장 + 역할 확인 후 진입(공통). */
  const finishLogin = async (token: string) => {
    localStorage.setItem('mall_admin_token', token)
    const me: any = await getMe().catch(() => null)
    if (me?.role) localStorage.setItem('mall_role', me.role)
    if (me?.username) localStorage.setItem('mall_admin_user', me.username)
    if (me?.role === 'USER') { setErr(t('admin.login.errNoPriv')); localStorage.removeItem('mall_admin_token'); return }
    nav('/admin/dashboard')
  }

  const submitLogin = async (e: React.FormEvent) => {
    e.preventDefault(); setErr('')
    try {
      const res = await login(username, password)
      const data = res.data?.data || {}
      if (data.twofa === 'true') {
        // 운영 계정 2FA — 코드 입력 단계로 전환(코드는 메일/로그로만 발송, 화면 미표시)
        setVerifyToken(data.verifyToken || '')
        setMaskedEmail(data.maskedEmail || '')
        setStep('verify')
        return
      }
      const token = data.token
      if (!token) throw new Error('no token')
      await finishLogin(token)
    } catch {
      setErr(t('admin.login.errFailed'))
    }
  }

  const submitVerify = async (e: React.FormEvent) => {
    e.preventDefault(); setErr('')
    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('인증 코드가 올바르지 않거나 만료되었습니다. (Invalid or expired code)')
    }
  }

  return (
    <div className="admin-shell min-h-screen flex items-center justify-center bg-ink text-[#e6edf6]">
      <div className="absolute top-5 right-5"><LanguageSwitcher variant="admin" /></div>

      {step === 'login' ? (
        <form onSubmit={submitLogin} 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">{t('admin.login.title')}</span>
          </div>
          <p className="text-center text-sm text-slate-400 mb-6">{t('admin.login.subtitle')}</p>
          <label className="block text-xs text-slate-400 mb-1">{t('admin.login.username')}</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">{t('admin.login.password')}</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 className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90">{t('admin.login.signIn')}</button>
          <p className="text-center text-[11px] text-slate-500 mt-4">{t('admin.login.storefrontHere')} <a href="/" className="text-brand">{t('admin.login.here')}</a></p>
        </form>
      ) : (
        <form onSubmit={submitVerify} className="w-[360px] bg-panel border border-edge rounded-2xl p-8">
          <div className="flex items-center gap-2 justify-center mb-4">
            <span className="text-xl font-bold">2차 인증 / 2FA</span>
          </div>
          <p className="text-center text-sm text-slate-400 mb-2">운영 계정 보안을 위한 2차 인증입니다.</p>
          <p className="text-center text-[12px] text-slate-500 mb-6">
            인증 코드를 {maskedEmail || '등록된 이메일'} 로 보냈습니다.
          </p>
          <label className="block text-xs text-slate-400 mb-1">인증 코드 (6자리)</label>
          <input value={code} onChange={e => setCode(e.target.value)} inputMode="numeric" maxLength={6} autoFocus
            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 className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90">확인 / Verify</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-brand">← 돌아가기 / Back</button>
        </form>
      )}
    </div>
  )
}
