File size: 2,698 Bytes
9853b20 769d6f8 9853b20 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | 'use client'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useRouter } from 'next/navigation'
import { codeEntrySchema, type CodeEntryForm as CodeEntryFormType } from 'lib/validations/code'
export function CodeEntryForm() {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const router = useRouter()
const {
register,
handleSubmit,
formState: { errors }
} = useForm<CodeEntryFormType>({
resolver: zodResolver(codeEntrySchema)
})
const onSubmit = async (data: CodeEntryFormType) => {
try {
setLoading(true)
setError(null)
const response = await fetch('/api/codes/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: data.code.toUpperCase() })
})
const result = await response.json()
if (!response.ok) {
if (response.status === 429) {
setError('Příliš mnoho pokusů. Zkuste to později.')
} else if (response.status === 404) {
setError('Kód nenalezen. Zkontrolujte správnost zadání.')
} else {
setError(result.error || 'Nastala chyba při ověřování kódu.')
}
return
}
if (result.needsPin) {
router.push(`/enter-pin?code=${data.code.toUpperCase()}`)
} else if (result.roomId) {
router.push(`/room/${result.roomId}?code=${data.code.toUpperCase()}`)
} else {
router.push(`/setup?code=${data.code.toUpperCase()}`)
}
} catch {
setError('Došlo k neočekávané chybě.')
} finally {
setLoading(false)
}
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="form">
<input
{...register('code')}
type="text"
id="code"
name="code"
maxLength={5}
placeholder="Zadej kód pro vstup"
autoComplete="off"
aria-label="Kód místnosti"
className={errors.code ? 'error' : ''}
style={{ textTransform: 'uppercase' }}
/>
<input
type="submit"
value={loading ? 'Ověřuji...' : 'Vstoupit'}
disabled={loading}
/>
{error && (
<div
id="form-code-error"
className="error"
style={{
display: 'block',
marginTop: 8,
padding: '8px 10px',
background: '#FEE2E2',
color: '#991B1B',
borderRadius: 6,
fontWeight: 600
}}
>
{error}
</div>
)}
</form>
)
}
|