import { useState } from 'react'
import { signup, findId, resetPasswordRequest } from '../api/uiws'

/**
 * 로그인 보조기능 3종 모달(UIWS auth 패턴 이식, CMS 디자인토큰).
 * - 회원가입(signup): 승인 대기 안내. - 아이디찾기(find-id): 마스킹 username 표시.
 * - 비밀번호 초기화(reset): 임시비번 메일/로그 발송 안내(코드/비번 화면 무노출).
 * 디자인토큰: bg-ink/bg-panel/bg-card/border-edge/bg-brand/text-ink — Login.tsx 와 동일(다크 테마 정합).
 * 색상 하드코딩 없이 테마 토큰만 사용 → 모듈 스코프 격리, 전역 테마 무영향.
 */

export type AuthHelperKind = 'signup' | 'findId' | 'reset'

const field =
  'w-full mb-3 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none'
const labelCls = 'block text-xs text-slate-400 mb-1'

export default function AuthHelperModals({
  kind,
  onClose,
}: {
  kind: AuthHelperKind | null
  onClose: () => void
}) {
  if (!kind) return null
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="w-[360px] bg-panel border border-edge rounded-2xl p-6"
        onClick={e => e.stopPropagation()}
      >
        {kind === 'signup' && <SignupForm onClose={onClose} />}
        {kind === 'findId' && <FindIdForm onClose={onClose} />}
        {kind === 'reset' && <ResetForm onClose={onClose} />}
      </div>
    </div>
  )
}

function Header({ title }: { title: string }) {
  return <h3 className="text-base font-bold mb-4 text-slate-100">{title}</h3>
}

function CloseBtn({ onClose }: { onClose: () => void }) {
  return (
    <button
      type="button"
      onClick={onClose}
      className="w-full py-2 mt-2 rounded-lg text-slate-400 text-xs hover:text-slate-200"
    >
      닫기
    </button>
  )
}

function SignupForm({ onClose }: { onClose: () => void }) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [email, setEmail] = useState('')
  const [msg, setMsg] = useState('')
  const [ok, setOk] = useState(false)
  const [busy, setBusy] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setMsg(''); setBusy(true)
    try {
      const res = await signup({ username, password, displayName, email })
      const d = res.data?.data || {}
      setOk(!!d.success)
      setMsg(d.message || (d.success ? '가입 신청이 접수되었습니다.' : '가입 신청에 실패했습니다.'))
    } catch {
      setOk(false)
      setMsg('가입 신청에 실패했습니다. 입력값을 확인하세요.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={submit}>
      <Header title="운영자 회원가입" />
      <p className="text-[11px] text-slate-500 mb-4">가입 후 관리자 승인을 거쳐야 로그인할 수 있습니다.</p>
      <label className={labelCls}>아이디</label>
      <input value={username} onChange={e => setUsername(e.target.value)} className={field} required />
      <label className={labelCls}>비밀번호</label>
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} className={field} required />
      <label className={labelCls}>이름(표시명)</label>
      <input value={displayName} onChange={e => setDisplayName(e.target.value)} className={field} />
      <label className={labelCls}>이메일</label>
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} className={field} required />
      {msg && <p className={`text-xs mb-3 ${ok ? 'text-emerald-400' : 'text-rose-400'}`}>{msg}</p>}
      {!ok && (
        <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>
      )}
      <CloseBtn onClose={onClose} />
    </form>
  )
}

function FindIdForm({ onClose }: { onClose: () => void }) {
  const [displayName, setDisplayName] = useState('')
  const [email, setEmail] = useState('')
  const [result, setResult] = useState<string | null>(null)
  const [err, setErr] = useState('')
  const [busy, setBusy] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr(''); setResult(null); setBusy(true)
    try {
      const res = await findId({ displayName, email })
      const d = res.data?.data || {}
      if (d.found) setResult(d.maskedUsername || '')
      else setErr('일치하는 계정을 찾지 못했습니다. 이름·이메일을 확인하세요.')
    } catch {
      setErr('조회에 실패했습니다.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={submit}>
      <Header title="아이디 찾기" />
      <p className="text-[11px] text-slate-500 mb-4">가입 시 등록한 이름과 이메일로 아이디를 찾습니다.</p>
      <label className={labelCls}>이름(표시명)</label>
      <input value={displayName} onChange={e => setDisplayName(e.target.value)} className={field} required />
      <label className={labelCls}>이메일</label>
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} className={field} required />
      {result !== null && (
        <p className="text-xs mb-3 text-emerald-400">
          회원님의 아이디: <span className="font-mono tracking-wider">{result}</span>
        </p>
      )}
      {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>
      <CloseBtn onClose={onClose} />
    </form>
  )
}

function ResetForm({ onClose }: { onClose: () => void }) {
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [msg, setMsg] = useState('')
  const [ok, setOk] = useState(false)
  const [busy, setBusy] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setMsg(''); setBusy(true)
    try {
      const res = await resetPasswordRequest({ username, email })
      const d = res.data?.data || {}
      setOk(!!d.success)
      setMsg(d.message || '임시 비밀번호를 이메일로 발송했습니다.')
    } catch {
      setOk(false)
      setMsg('요청에 실패했습니다. 입력값을 확인하세요.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={submit}>
      <Header title="비밀번호 초기화" />
      <p className="text-[11px] text-slate-500 mb-4">아이디와 이메일을 확인 후 임시 비밀번호를 메일로 보내드립니다.</p>
      <label className={labelCls}>아이디</label>
      <input value={username} onChange={e => setUsername(e.target.value)} className={field} required />
      <label className={labelCls}>이메일</label>
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} className={field} required />
      {msg && <p className={`text-xs mb-3 ${ok ? 'text-emerald-400' : 'text-rose-400'}`}>{msg}</p>}
      {!ok && (
        <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>
      )}
      <CloseBtn onClose={onClose} />
    </form>
  )
}
