'use client'

import type { FormEvent } from 'react'
import { useEffect, useState } from 'react'
import { djangoUrl } from '@/lib/site-content'

export function VerifyForm() {
  const [message, setMessage] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [resending, setResending] = useState(false)

  useEffect(() => {
    if (!message) return
    const timer = window.setTimeout(() => setMessage(''), 7000)
    return () => window.clearTimeout(timer)
  }, [message])

  async function csrfToken() {
    const response = await fetch(djangoUrl('/csrf/'), { cache: 'no-store', credentials: 'include', headers: { Accept: 'application/json' } })
    const payload = await response.json().catch(() => null) as { csrfToken?: string } | null
    if (!response.ok || !payload?.csrfToken) throw new Error('The verification service is unavailable. Please try again.')
    return payload.csrfToken
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setMessage('')
    setSubmitting(true)
    try {
      const token = await csrfToken()
      const code = String(new FormData(event.currentTarget).get('code') || '')
      const response = await fetch(djangoUrl('/api/auth/verify/'), {
        method: 'POST',
        credentials: 'include',
        headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': token },
        body: JSON.stringify({ code }),
      })
      const payload = await response.json().catch(() => null) as { detail?: string; redirectUrl?: string } | null
      if (!response.ok) {
        setMessage(payload?.detail || 'That code could not be verified.')
        return
      }
      window.location.assign(payload?.redirectUrl || '/login?verified=1')
    } catch (error) {
      setMessage(error instanceof Error ? error.message : 'We could not connect to the verification service.')
    } finally {
      setSubmitting(false)
    }
  }

  async function resendCode() {
    setMessage('')
    setResending(true)
    try {
      const token = await csrfToken()
      const response = await fetch(djangoUrl('/api/auth/verify/resend/'), {
        method: 'POST',
        credentials: 'include',
        headers: { Accept: 'application/json', 'X-CSRFToken': token },
      })
      const payload = await response.json().catch(() => null) as { detail?: string } | null
      setMessage(payload?.detail || (response.ok ? 'A new verification code was sent.' : 'We could not resend the code.'))
    } catch (error) {
      setMessage(error instanceof Error ? error.message : 'We could not connect to the verification service.')
    } finally {
      setResending(false)
    }
  }

  return <div className="mt-8">
    {message && <p role="alert" className="mb-5 rounded-2xl border border-[var(--teal)]/30 bg-[var(--mist)] px-4 py-3 text-sm font-semibold text-[var(--navy)]">{message}</p>}
    <form onSubmit={handleSubmit} className="flex flex-col gap-5" noValidate>
      <label className="text-sm font-semibold">Six-digit code<input className="form-input tracking-[.35em]" name="code" inputMode="numeric" autoComplete="one-time-code" maxLength={6} pattern="[0-9]{6}" placeholder="000000" required /></label>
      <button className="rounded-full bg-[var(--navy)] px-5 py-3.5 text-sm font-bold text-white disabled:cursor-wait disabled:opacity-60" type="submit" disabled={submitting}>{submitting ? 'Checking code…' : 'Verify email'}</button>
    </form>
    <button type="button" onClick={resendCode} disabled={resending} className="mt-4 w-full rounded-full border border-[var(--line)] px-5 py-3 text-sm font-bold text-[var(--navy)] disabled:cursor-wait disabled:opacity-60">{resending ? 'Sending…' : 'Send a new code'}</button>
    <a href="/register" className="mt-5 block text-center text-sm font-semibold text-[var(--teal)]">Start registration again</a>
  </div>
}
