'use client'

import { useState } from 'react'
import { getTranslation, type Language } from '@/lib/i18n'

const CMS = (process.env.NEXT_PUBLIC_CMS_URL || 'https://cms.kevinvictorrealestate.com').replace(
  /\/+$/,
  ''
)

interface Props {
  rentalId: string
  lang: Language
  maxGuests?: number | null
  minNights: number
}

/**
 * Formulario "Reserve Direct" del detalle de una rental.
 *
 * No hay pasarela de pago: la reserva se confirma por correo. El honeypot va
 * oculto, igual que en el alta de propiedad.
 */
export default function InquiryForm({ rentalId, lang, maxGuests, minNights }: Props) {
  const t = (k: string) => getTranslation(lang, k)
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [website, setWebsite] = useState('')

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setBusy(true)
    setError(null)

    const fd = new FormData(e.currentTarget)
    const body = {
      rentalId,
      name: String(fd.get('name') || ''),
      email: String(fd.get('email') || ''),
      phone: String(fd.get('phone') || '') || undefined,
      message: String(fd.get('message') || '') || undefined,
      checkIn: String(fd.get('checkIn') || '') || undefined,
      checkOut: String(fd.get('checkOut') || '') || undefined,
      guests: fd.get('guests') ? Number(fd.get('guests')) : undefined,
      source: 'RENTAL_DETAIL',
      language: lang,
      website: website || undefined,
    }

    try {
      const res = await fetch(`${CMS}/api/public/inquiries/`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      if (!res.ok) {
        const json = await res.json().catch(() => ({}))
        setError(
          (json.detail as string) ||
            (json.error as string) ||
            // 429 = rate limit. El texto lo dice para que el visitante sepa
            // que espere, no piense que falló el formulario.
            (res.status === 429 ? 'Too many requests. Please try again later.' : t('rentals.errorGeneric'))
        )
        return
      }
      setDone(true)
    } catch {
      setError(t('rentals.errorGeneric'))
    } finally {
      setBusy(false)
    }
  }

  if (done) {
    return (
      <div className="rounded-lg border border-green-200 bg-green-50 p-6 text-center">
        <p className="font-semibold text-green-900">{t('rentals.inquirySuccess')}</p>
      </div>
    )
  }

  const input =
    'w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-brand-primary focus:outline-none'

  return (
    <form onSubmit={submit} className="space-y-3">
      <div>
        <label className="mb-1 block text-sm font-medium" htmlFor="iq-name">
          {t('rentals.yourName')}
        </label>
        <input id="iq-name" name="name" required minLength={2} className={input} />
      </div>

      <div>
        <label className="mb-1 block text-sm font-medium" htmlFor="iq-email">
          {t('rentals.yourEmail')}
        </label>
        <input id="iq-email" name="email" type="email" required className={input} />
      </div>

      <div>
        <label className="mb-1 block text-sm font-medium" htmlFor="iq-phone">
          {t('rentals.yourPhone')}
        </label>
        <input id="iq-phone" name="phone" className={input} />
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="mb-1 block text-sm font-medium" htmlFor="iq-in">
            {t('rentals.checkIn')}
          </label>
          <input id="iq-in" name="checkIn" type="date" className={input} />
        </div>
        <div>
          <label className="mb-1 block text-sm font-medium" htmlFor="iq-out">
            {t('rentals.checkOut')}
          </label>
          <input id="iq-out" name="checkOut" type="date" className={input} />
        </div>
      </div>

      {maxGuests != null && (
        <div>
          <label className="mb-1 block text-sm font-medium" htmlFor="iq-guests">
            {t('rentals.guests')}
          </label>
          <input
            id="iq-guests"
            name="guests"
            type="number"
            min={1}
            max={maxGuests}
            defaultValue={maxGuests}
            className={input}
          />
        </div>
      )}

      <div>
        <label className="mb-1 block text-sm font-medium" htmlFor="iq-msg">
          {t('rentals.yourMessage')}
        </label>
        <textarea id="iq-msg" name="message" rows={4} className={input} />
      </div>

      {/* Honeypot */}
      <div className="hidden" aria-hidden="true">
        <label htmlFor="iq-website">{t('rentals.honeypotLabel')}</label>
        <input
          id="iq-website"
          tabIndex={-1}
          autoComplete="off"
          value={website}
          onChange={(e) => setWebsite(e.target.value)}
        />
      </div>

      {error && (
        <p role="alert" className="rounded bg-red-50 p-3 text-sm text-red-700">
          {error}
        </p>
      )}

      <button
        type="submit"
        disabled={busy}
        className="w-full rounded-lg bg-brand-primary px-5 py-3 font-semibold text-white transition hover:bg-brand-darkGreen disabled:opacity-50"
      >
        {t('rentals.submitInquiry')}
      </button>

      <p className="text-xs text-gray-500">
        {t('rentals.minNights')}: {minNights}
      </p>
    </form>
  )
}