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

const FLIGHT_PRICE = 699

export function TastingFlight({ brews }: { brews: Brew[] }) {
  const [selected, setSelected] = React.useState<Set<string>>(
    () => new Set(brews.slice(0, 4).map((brew) => brew.uid)),
  )
  const [status, setStatus] = React.useState<'idle' | 'sending' | 'done' | 'error'>('idle')

  function toggle(uid: string) {
    setSelected((current) => {
      const next = new Set(current)
      if (next.has(uid)) {
        next.delete(uid)
      } else {
        next.add(uid)
      }
      return next
    })
  }

  async function handleSubmit() {
    const chosen = brews.filter((brew) => selected.has(brew.uid))
    if (chosen.length === 0) return
    setStatus('sending')
    try {
      await createReservation({
        data: {
          name: 'Tasting Flight Request',
          phone: '-',
          source: 'flight',
          requests: `Custom flight (${chosen.length} x 150ml): ${chosen
            .map((brew) => brew.name)
            .join(', ')}`,
        },
      })
      setStatus('done')
    } catch {
      setStatus('error')
    }
  }

  if (status === 'done') {
    return (
      <div className="flex flex-col items-center gap-space-md rounded-xl bg-surface p-space-xl text-center shadow-2xl">
        <span className="material-symbols-outlined text-[48px] text-primary">sports_bar</span>
        <h2 className="font-headline-lg text-on-surface">Your custom flight is on its way</h2>
        <p className="text-body-md text-on-surface-variant">
          We've sent your tasting flight to the bar. See you soon!
        </p>
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-space-lg rounded-xl bg-surface p-space-xl shadow-2xl">
      <div className="flex flex-col gap-space-xs text-center">
        <span className="text-label-lg uppercase tracking-widest text-primary">
          Taproom Experience
        </span>
        <h2 className="font-headline-lg text-on-surface">Build Your Custom Tasting Flight</h2>
        <p className="text-body-md text-on-surface-variant">
          Select any 4 brews for our signature wooden sampling paddle (150ml each).
        </p>
      </div>
      <div className="grid grid-cols-1 gap-space-md sm:grid-cols-2 md:grid-cols-3">
        {brews.map((brew) => (
          <label
            key={brew.uid}
            className="flex cursor-pointer items-center justify-between rounded-lg bg-surface-container p-space-md transition-colors hover:bg-surface-container-high"
          >
            <div className="flex items-center gap-space-md">
              <input
                checked={selected.has(brew.uid)}
                className="h-5 w-5 cursor-pointer rounded accent-primary"
                type="checkbox"
                onChange={() => toggle(brew.uid)}
              />
              <span className="text-body-md font-medium text-on-surface">{brew.short_name}</span>
            </div>
            <span className="text-label-md text-primary">{brew.abv}%</span>
          </label>
        ))}
      </div>
      <div className="flex flex-col items-center justify-between gap-space-md border-t border-outline-variant/20 pt-space-md sm:flex-row">
        <div className="text-body-sm text-on-surface-variant">
          Flight Price:{' '}
          <span className="font-bold text-headline-md text-on-surface">₹{FLIGHT_PRICE}</span>{' '}
          <span className="text-xs">(4 x 150ml pours)</span>
        </div>
        <button
          className="w-full rounded-lg bg-primary px-space-xl py-space-md text-label-lg font-medium text-on-primary shadow-lg transition-all hover:bg-primary/90 disabled:opacity-60 sm:w-auto"
          type="button"
          disabled={status === 'sending' || selected.size !== 4}
          onClick={handleSubmit}
        >
          {status === 'sending'
            ? 'Reserving…'
            : selected.size === 4
              ? 'Reserve Tasting Flight'
              : `Select ${4 - selected.size} more brew${selected.size === 3 ? '' : 's'}`}
        </button>
      </div>
      {status === 'error' ? (
        <p className="text-body-sm text-error">
          Could not submit your flight right now — please try again or ask your server.
        </p>
      ) : null}
    </div>
  )
}
