'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Turnstile } from '@/components/Turnstile'

const ERROR_KEYS = [
  'missingFields',
  'passwordMismatch',
  'passwordTooLong',
  'invalidEmail',
  'emailExists',
  'recruiterNotFound',
  'captchaFailed',
] as const
const SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY

export function RegisterForm() {
  const t = useTranslations('Register')
  const [form, setForm] = useState({ password: '', confPassword: '', email: '', confEmail: '', recruiter: '' })
  const [accepted, setAccepted] = useState(false)
  const [busy, setBusy] = useState(false)
  const [captcha, setCaptcha] = useState('')
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  function upd(k: string, v: string) {
    setForm((f) => ({ ...f, [k]: v }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !accepted) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ ...form, turnstileToken: captcha }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('success') })
      } else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
    } finally {
      setBusy(false)
    }
  }

  const input = 'nw-input'

  return (
    <div className="mx-auto max-w-sm">
      <p className="mb-4 text-sm text-amber-200/70">{t('info')}</p>
      <form onSubmit={handleSubmit} className="space-y-3">
        <input type="password" maxLength={16} placeholder={t('password')} value={form.password} onChange={(e) => upd('password', e.target.value)} className={input} />
        <input type="password" maxLength={16} placeholder={t('confPassword')} value={form.confPassword} onChange={(e) => upd('confPassword', e.target.value)} className={input} />
        <input type="email" placeholder={t('email')} value={form.email} onChange={(e) => upd('email', e.target.value)} className={input} />
        <input type="email" placeholder={t('confEmail')} value={form.confEmail} onChange={(e) => upd('confEmail', e.target.value)} className={input} />
        <input type="text" maxLength={12} placeholder={t('recruiter')} value={form.recruiter} onChange={(e) => upd('recruiter', e.target.value)} className={input} />
        <label className="flex items-start gap-2 text-left text-sm">
          <input type="checkbox" checked={accepted} onChange={(e) => setAccepted(e.target.checked)} className="mt-1" />
          <span>{t('terms')}</span>
        </label>
        <Turnstile onVerify={setCaptcha} />
        <button type="submit" disabled={busy || !accepted || (!!SITE_KEY && !captcha)} className="w-full nw-btn disabled:opacity-60">
          {busy ? t('creating') : t('submit')}
        </button>
      </form>
      {message && <p className={`mt-3 text-center ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
    </div>
  )
}
