import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { findId } from '../api/uiws'

/**
 * 아이디 찾기 화면(UIWS 로그인 보조 이식). 이름+이메일 일치 시 마스킹된 아이디(예: ad***)만 반환.
 * 원문 아이디는 절대 노출하지 않는다(자격증명 보호 불변규칙).
 */
export default function FindId() {
  const navigate = useNavigate()
  const [displayName, setDisplayName] = useState('')
  const [email, setEmail]             = useState('')
  const [result, setResult]           = useState<string | null>(null)
  const [notFound, setNotFound]       = useState(false)
  const [loading, setLoading]         = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true); setResult(null); setNotFound(false)
    try {
      const res = await findId({ displayName, email })
      const data = res.data?.data
      if (data?.found) setResult(data.maskedUsername)
      else setNotFound(true)
    } catch {
      setNotFound(true)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-ink flex items-center justify-center">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-brand">아이디 찾기</h1>
          <p className="text-sm text-gray-400 mt-1">이름과 이메일로 아이디를 확인합니다.</p>
        </div>
        <form onSubmit={handleSubmit} className="bg-card border border-edge rounded-lg p-6 space-y-4">
          <div>
            <label className="block text-xs text-gray-400 mb-1">이름</label>
            <input value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder="홍길동"
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-brand focus:outline-none" />
          </div>
          <div>
            <label className="block text-xs text-gray-400 mb-1">이메일</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="user@zioinfo.co.kr"
              className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-brand focus:outline-none" />
          </div>
          {result && (
            <p className="text-xs text-accent">
              회원님의 아이디: <span className="font-mono font-bold tracking-wider">{result}</span>
            </p>
          )}
          {notFound && <p className="text-xs text-red-400">일치하는 계정을 찾을 수 없습니다.</p>}
          <button type="submit" disabled={loading}
            className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm font-medium transition-colors disabled:opacity-50">
            {loading ? '확인 중...' : '아이디 찾기'}
          </button>
          <button type="button" onClick={() => navigate('/login')}
            className="w-full border border-edge text-gray-400 hover:text-white py-2 rounded text-sm transition-colors">
            로그인으로
          </button>
          <div className="text-center text-xs text-gray-400 pt-1">
            <Link to="/signup" className="hover:text-brand">회원가입</Link>
            <span className="text-edge mx-2">|</span>
            <Link to="/reset-pw" className="hover:text-brand">비밀번호 초기화</Link>
          </div>
        </form>
      </div>
    </div>
  )
}
