'use client'

import type { FormEvent } from 'react'

export function ContactForm({ action }: { action: string }) {
  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    const form = event.currentTarget
    event.preventDefault()
    const csrfUrl = new URL('/csrf/', action)
    const response = await fetch(csrfUrl, { cache: 'no-store', credentials: 'include' }).catch(() => null)
    const token = response?.ok ? String((await response.json()).csrfToken ?? '') : ''
    if (!token) {
      window.location.href = action
      return
    }
    form.querySelectorAll('input[name="csrfmiddlewaretoken"]').forEach((input) => input.remove())
    const input = document.createElement('input')
    input.type = 'hidden'
    input.name = 'csrfmiddlewaretoken'
    input.value = token
    form.appendChild(input)
    form.submit()
  }

  return <form action={action} method="post" onSubmit={handleSubmit} className="rounded-[2rem] border border-[var(--line)] bg-white p-6 shadow-sm sm:p-9">
    <input type="hidden" name="consent" value="on" />
    <div className="grid gap-5 sm:grid-cols-2">
      <label className="text-sm font-semibold text-[var(--navy)]">Full name<input className="form-input" name="full_name" type="text" autoComplete="name" required /></label>
      <label className="text-sm font-semibold text-[var(--navy)]">Email address<input className="form-input" name="email" type="email" autoComplete="email" required /></label>
    </div>
    <div className="mt-5 grid gap-5 sm:grid-cols-2">
      <label className="text-sm font-semibold text-[var(--navy)]">Telephone<input className="form-input" name="telephone" type="tel" autoComplete="tel" /></label>
      <label className="text-sm font-semibold text-[var(--navy)]">Enquiry type<select className="form-input" name="subject" defaultValue="General enquiry"><option>General enquiry</option><option>Fingerling order</option><option>Fish-farm training</option><option>Partnership enquiry</option></select></label>
    </div>
    <label className="mt-5 block text-sm font-semibold text-[var(--navy)]">Message<textarea className="form-input min-h-36 resize-y" name="message" required /></label>
    <button type="submit" className="mt-7 inline-flex rounded-full bg-gradient-to-r from-[var(--teal)] to-[var(--navy)] px-7 py-3.5 text-sm font-bold text-white shadow-md transition duration-300 hover:-translate-y-1 hover:shadow-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--teal)] focus-visible:ring-offset-2">Send message</button>
  </form>
}
