'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>
  )
}
