import * as React from 'react'
import { createReservation } from '~/lib/data'

export function QuickReserveForm() {
  const [name, setName] = React.useState('')
  const [phone, setPhone] = React.useState('')
  const [status, setStatus] = React.useState<'idle' | 'sending' | 'done' | 'error'>('idle')

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault()
    setStatus('sending')
    try {
      await createReservation({ data: { name, phone, source: 'quick' } })
      setStatus('done')
      setName('')
      setPhone('')
    } catch {
      setStatus('error')
    }
  }

  if (status === 'done') {
    return (
      <div className="flex items-center justify-center gap-space-sm rounded-xl bg-surface-container p-space-lg text-body-md text-primary">
        <span className="material-symbols-outlined">check_circle</span>
        Reservation request received! We will contact you shortly.
      </div>
    )
  }

  return (
    <form
      className="flex flex-col gap-space-md rounded-xl bg-surface-container p-space-lg md:flex-row"
      onSubmit={handleSubmit}
    >
      <input
        className="flex-1 rounded bg-surface-container-highest px-space-md py-space-sm text-on-surface placeholder:text-on-surface-variant/50 focus:outline-none focus:ring-1 focus:ring-primary"
        placeholder="Your Name"
        required
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        className="flex-1 rounded bg-surface-container-highest px-space-md py-space-sm text-on-surface placeholder:text-on-surface-variant/50 focus:outline-none focus:ring-1 focus:ring-primary"
        placeholder="Phone Number"
        required
        type="tel"
        value={phone}
        onChange={(e) => setPhone(e.target.value)}
      />
      <button
        className="rounded bg-primary px-space-lg py-space-sm font-label-lg text-on-primary transition-all hover:bg-primary-container"
        type="submit"
        disabled={status === 'sending'}
      >
        {status === 'sending' ? 'Booking…' : 'Book Table'}
      </button>
      {status === 'error' ? (
        <p className="text-body-sm text-error md:hidden">
          Something went wrong — please call us instead.
        </p>
      ) : null}
    </form>
  )
}
