import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Cpu } from 'lucide-react'
import { login, getMe } from '../api/client'
import { verify2fa, signup, findId, resetPassword } from '../api/uiws'

type HelperMode = 'signup' | 'find-id' | 'reset-password'

/**
 * GUARDiA MES 로그인 — UIWS 2FA 레이어 대응.
 * 1차 login 응답이 twofa="true" 면 인증코드 입력 단계로 전환(verifyToken 보관) →
 * /api/mes/auth/verify 로 코드 검증 후 access 토큰 저장. twofa!="true"(off)면 즉시 로그인(회귀 0).
 * 인증코드는 서버 로그/메일로만 전달 — 화면/응답에 코드 노출 없음.
 */
export default function Login() {
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [err, setErr] = useState('')
  const [busy, setBusy] = useState(false)
  const [step, setStep] = useState<'login' | 'verify'>('login')
  const [verifyToken, setVerifyToken] = useState('')
  const [maskedEmail, setMaskedEmail] = useState('')
  const [code, setCode] = useState('')
  const nav = useNavigate()

  // ── 로그인 보조 3종(회원가입/아이디찾기/비밀번호초기화) 모달 상태 ──────────────
  const [helper, setHelper] = useState<HelperMode | null>(null)
  const [hForm, setHForm] = useState({ username: '', password: '', displayName: '', email: '' })
  const [hBusy, setHBusy] = useState(false)
  const [hMsg, setHMsg] = useState('')        // 결과 안내(성공/실패 공통)
  const [hErr, setHErr] = useState(false)      // 메시지 톤(에러 여부)

  const openHelper = (mode: HelperMode) => {
    setHelper(mode); setHForm({ username: '', password: '', displayName: '', email: '' })
    setHMsg(''); setHErr(false)
  }
  const closeHelper = () => { setHelper(null); setHMsg(''); setHErr(false) }

  // 보조 기능 제출 — 응답 봉투 {success,message,data}. 임시비번/존재여부는 서버가 메시지로만 안내.
  const submitHelper = async (e: React.FormEvent) => {
    e.preventDefault()
    setHBusy(true); setHMsg(''); setHErr(false)
    try {
      let res
      if (helper === 'signup') {
        res = await signup({ username: hForm.username.trim(), password: hForm.password,
          displayName: hForm.displayName.trim() || undefined, email: hForm.email.trim() })
        const d = res.data?.data
        setHErr(!d?.success); setHMsg(d?.message || '처리되었습니다.')
      } else if (helper === 'find-id') {
        res = await findId({ displayName: hForm.displayName.trim(), email: hForm.email.trim() })
        const d = res.data?.data
        if (d?.found) { setHErr(false); setHMsg(`회원님의 아이디는 [${d.maskedUsername}] 입니다.`) }
        else { setHErr(true); setHMsg('일치하는 계정을 찾을 수 없습니다. 이름과 이메일을 확인하세요.') }
      } else if (helper === 'reset-password') {
        res = await resetPassword({ username: hForm.username.trim(), email: hForm.email.trim() })
        const d = res.data?.data
        setHErr(!d?.success); setHMsg(d?.message || '요청이 처리되었습니다.')
      }
    } catch {
      setHErr(true); setHMsg('요청 처리 중 오류가 발생했습니다. 잠시 후 다시 시도하세요.')
    } finally {
      setHBusy(false)
    }
  }

  const helperTitle = helper === 'signup' ? '회원가입(승인 대기)'
    : helper === 'find-id' ? '아이디 찾기' : '비밀번호 초기화'

  // access 토큰 저장 + getMe 로 role/username 보관(Sidebar RBAC 가드 의존) → 대시보드 이동
  const finish = async (token?: string) => {
    if (!token) throw new Error('no token')
    localStorage.setItem('mes_token', token)
    try {
      const me = await getMe()
      const d = me.data?.data || {}
      if (d.role) localStorage.setItem('mes_role', d.role)
      if (d.username) localStorage.setItem('mes_user', d.username)
    } catch { /* noop */ }
    nav('/dashboard')
  }

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr(''); setBusy(true)
    try {
      const res = await login(username, password)
      const data = res.data?.data || {}
      if (data.twofa === 'true') {
        // 2단계: verify-token 보관 후 코드 입력 화면으로(코드는 미표시)
        setVerifyToken(data.verifyToken)
        setMaskedEmail(data.maskedEmail || '')
        setStep('verify')
        return
      }
      await finish(data.token)
    } catch {
      setErr('로그인 실패 — 아이디/비밀번호를 확인하세요.')
    } finally {
      setBusy(false)
    }
  }

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

  return (
    <div className="min-h-screen flex items-center justify-center bg-ink">
      <form onSubmit={step === 'login' ? submit : submitCode}
        className="w-[360px] bg-panel border border-edge rounded-2xl p-8">
        <div className="flex items-center gap-2 justify-center mb-6">
          <Cpu className="text-brand" size={32} />
          <span className="text-xl font-bold">GUARDiA MES</span>
        </div>
        <p className="text-center text-sm text-slate-400 mb-6">AI 제조실행시스템 · WMS · MES · QMS</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" />
          </>
        ) : (
          <>
            <p className="text-xs text-slate-400 mb-3">
              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" autoFocus placeholder="6자리 코드"
              className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none tracking-widest" />
          </>
        )}

        {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 ? '처리 중…' : (step === 'login' ? '로그인' : '인증 확인')}
        </button>
        {step === 'verify' && (
          <button type="button" onClick={() => { setStep('login'); setCode(''); setErr('') }}
            className="w-full mt-2 py-2 rounded-lg text-xs text-slate-400 hover:text-slate-200">
            ← 처음으로
          </button>
        )}
        {step === 'login' && (
          <>
            {/* 로그인 보조 3종 링크 (UIWS auth 패턴 이식) */}
            <div className="flex items-center justify-center gap-2 text-[11px] text-slate-400 mt-4">
              <button type="button" onClick={() => openHelper('signup')} className="hover:text-brand">회원가입</button>
              <span className="text-slate-600">|</span>
              <button type="button" onClick={() => openHelper('find-id')} className="hover:text-brand">아이디 찾기</button>
              <span className="text-slate-600">|</span>
              <button type="button" onClick={() => openHelper('reset-password')} className="hover:text-brand">비밀번호 초기화</button>
            </div>
            <p className="text-center text-[11px] text-slate-500 mt-3">admin / manager / worker · admin123</p>
          </>
        )}
      </form>

      {/* 로그인 보조 모달 (MES 다크 테마 토큰 재사용 — 하드코딩 색상 없음) */}
      {helper && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
          onClick={closeHelper}>
          <form onClick={e => e.stopPropagation()} onSubmit={submitHelper}
            className="w-[360px] bg-panel border border-edge rounded-2xl p-7">
            <div className="flex items-center justify-between mb-5">
              <span className="text-base font-bold">{helperTitle}</span>
              <button type="button" onClick={closeHelper}
                className="text-slate-400 hover:text-slate-200 text-lg leading-none">×</button>
            </div>

            {/* 회원가입: 아이디·비번·이름·이메일 / 아이디찾기: 이름·이메일 / 비번초기화: 아이디·이메일 */}
            {(helper === 'signup' || helper === 'reset-password') && (
              <>
                <label className="block text-xs text-slate-400 mb-1">아이디</label>
                <input value={hForm.username} onChange={e => setHForm({ ...hForm, username: e.target.value })}
                  className="w-full mb-3 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
              </>
            )}
            {helper === 'signup' && (
              <>
                <label className="block text-xs text-slate-400 mb-1">비밀번호 (4자 이상)</label>
                <input type="password" value={hForm.password} onChange={e => setHForm({ ...hForm, password: e.target.value })}
                  className="w-full mb-3 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
              </>
            )}
            {(helper === 'signup' || helper === 'find-id') && (
              <>
                <label className="block text-xs text-slate-400 mb-1">이름</label>
                <input value={hForm.displayName} onChange={e => setHForm({ ...hForm, displayName: e.target.value })}
                  className="w-full mb-3 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="email" value={hForm.email} onChange={e => setHForm({ ...hForm, email: 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" />

            {hMsg && (
              <p className={`text-xs mb-3 ${hErr ? 'text-rose-400' : 'text-emerald-400'}`}>{hMsg}</p>
            )}
            <button disabled={hBusy}
              className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90 disabled:opacity-60">
              {hBusy ? '처리 중…' : (helper === 'signup' ? '가입 신청' : helper === 'find-id' ? '아이디 찾기' : '초기화 요청')}
            </button>
            {helper === 'signup' && (
              <p className="text-[11px] text-slate-500 mt-3">가입 후 관리자 승인이 완료되어야 로그인할 수 있습니다.</p>
            )}
          </form>
        </div>
      )}
    </div>
  )
}
