'use client'

import type { FormEvent } from 'react'
import { useEffect, useState } from 'react'
import { djangoUrl } from '@/lib/site-content'

type FieldErrors = Record<string, string[]>

function firstError(errors: FieldErrors, field: string) {
  return errors[field]?.[0]
}

export function RegisterForm() {
  const [errors, setErrors] = useState<FieldErrors>({})
  const [message, setMessage] = useState('')
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (!message) return
    const timer = window.setTimeout(() => setMessage(''), 7000)
    return () => window.clearTimeout(timer)
  }, [message])

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setErrors({})
    setMessage('')
    setSubmitting(true)

    try {
      const csrfResponse = await fetch(djangoUrl('/csrf/'), {
        cache: 'no-store',
        credentials: 'include',
        headers: { Accept: 'application/json' },
      })
      const csrfPayload = await csrfResponse.json().catch(() => null) as { csrfToken?: string } | null
      if (!csrfResponse.ok || !csrfPayload?.csrfToken) {
        throw new Error('The registration service is unavailable. Please try again.')
      }

      const body = new URLSearchParams()
      new FormData(event.currentTarget).forEach((value, key) => body.append(key, String(value)))
      body.set('csrfmiddlewaretoken', csrfPayload.csrfToken)

      const response = await fetch(djangoUrl('/api/auth/register/'), {
        method: 'POST',
        credentials: 'include',
        headers: { Accept: 'application/json' },
        body,
      })
      const payload = await response.json().catch(() => null) as { detail?: string; errors?: FieldErrors; verificationUrl?: string } | null

      if (!response.ok) {
        setErrors(payload?.errors ?? {})
        setMessage(payload?.detail ?? 'We could not create your account. Please try again.')
        return
      }

      window.location.assign(payload?.verificationUrl || '/register/verify')
    } catch (error) {
      setMessage(error instanceof Error ? error.message : 'We could not connect to the registration service.')
    } finally {
      setSubmitting(false)
    }
  }

  return <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-5" noValidate>
    {message && <p className="rounded-xl bg-[#fff0ee] px-4 py-3 text-sm text-[#b42318]" role="alert">{message}</p>}
    <label className="text-sm font-semibold">Full name<input className="form-input" name="full_name" type="text" autoComplete="name" required aria-invalid={Boolean(firstError(errors, 'full_name'))} />{firstError(errors, 'full_name') && <span className="mt-1 block text-xs font-normal text-[#b42318]">{firstError(errors, 'full_name')}</span>}</label>
    <label className="text-sm font-semibold">Email address<input className="form-input" name="email" type="email" autoComplete="email" required aria-invalid={Boolean(firstError(errors, 'email'))} />{firstError(errors, 'email') && <span className="mt-1 block text-xs font-normal text-[#b42318]">{firstError(errors, 'email')}</span>}</label>
    <label className="text-sm font-semibold">Telephone <span className="font-normal text-[var(--ink-soft)]">(optional)</span><input className="form-input" name="telephone" type="tel" autoComplete="tel" /></label>
    <label className="text-sm font-semibold">Account type<select className="form-input" name="account_type" defaultValue="customer"><option value="customer">Customer</option><option value="partner">Partner</option></select>{firstError(errors, 'account_type') && <span className="mt-1 block text-xs font-normal text-[#b42318]">{firstError(errors, 'account_type')}</span>}</label>
    <label className="text-sm font-semibold">Password<input className="form-input" name="password1" type="password" autoComplete="new-password" required aria-invalid={Boolean(firstError(errors, 'password1'))} />{firstError(errors, 'password1') && <span className="mt-1 block text-xs font-normal text-[#b42318]">{firstError(errors, 'password1')}</span>}</label>
    <label className="text-sm font-semibold">Confirm password<input className="form-input" name="password2" type="password" autoComplete="new-password" required aria-invalid={Boolean(firstError(errors, 'password2'))} />{firstError(errors, 'password2') && <span className="mt-1 block text-xs font-normal text-[#b42318]">{firstError(errors, 'password2')}</span>}</label>
    <label className="flex items-start gap-3 text-sm font-normal leading-6 text-[var(--ink-soft)]"><input className="mt-1 size-4 accent-[var(--teal)]" name="terms" type="checkbox" required /> <span>I agree to the account terms and consent to being contacted about my account.</span></label>
    {firstError(errors, 'terms') && <span className="-mt-3 text-xs text-[#b42318]">{firstError(errors, 'terms')}</span>}
    <button className="rounded-full bg-[var(--teal)] px-5 py-3.5 text-sm font-bold text-white disabled:cursor-not-allowed disabled:opacity-60" type="submit" disabled={submitting}>{submitting ? 'Creating account...' : 'Create account'}</button>
    <p className="text-center text-sm text-[var(--ink-soft)]">Already registered? <a href="/login" className="font-semibold text-[var(--teal)]">Sign in</a></p>
  </form>
}
