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

/**
 * 회원가입 화면(UIWS 로그인 보조 이식). 승인 대기(approved=false) 등록 → 관리자 승인 후 로그인.
 * 색상은 ESN Tailwind 테마 토큰만 사용. 비밀번호·자격증명은 응답에 노출되지 않는다.
 */
export default function Signup() {
  const navigate = useNavigate()
  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 [loading, setLoading]         = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true); setMsg('')
    try {
      const res = await signup({ username, password, displayName, email })
      const data = res.data?.data
      setOk(!!data?.success)
      setMsg(data?.message || '처리되었습니다.')
    } catch {
      setOk(false)
      setMsg('가입 신청 처리 중 오류가 발생했습니다.')
    } 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={username} onChange={e => setUsername(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">비밀번호 (4자 이상)</label>
            <input type="password" value={password} onChange={e => setPassword(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 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>
          {msg && <p className={`text-xs ${ok ? 'text-accent' : 'text-red-400'}`}>{msg}</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="/find-id" 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>
  )
}
