'use client'
import { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import Image from 'next/image'
import Link from 'next/link'
import { ArrowLeft, CalendarCheck, CircleCheck, Loader2 } from 'lucide-react'

const TIME_SLOTS = ['08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00']
const CURRENCY_SYMBOLS: Record<string, string> = { zar: 'R', usd: '$', eur: '€', gbp: '£', kes: 'KSh', ngn: '₦', ghs: '₵' }
const formatPrice = (amount: number, code?: string) => {
  const sym = CURRENCY_SYMBOLS[(code ?? '').toLowerCase()] ?? (code?.toUpperCase() ?? '')
  return `${sym}${(amount / 100).toFixed(0)}`
}

interface Service {
  id: string; title: string; description: string; thumbnail: string
  variants: { id: string; prices: { amount: number; currency_code: string }[] }[]
}

export default function BookingPage() {
  const params = useParams()
  const productId = params.productId as string

  const [service, setService] = useState<Service | null>(null)
  const [loadingSvc, setLoadingSvc] = useState(true)
  const [form, setForm] = useState({ name: '', email: '', phone: '', date: '', time: '', notes: '' })
  const [bookedSlots, setBookedSlots] = useState<string[]>([])
  const [loadingSlots, setLoadingSlots] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [confirmationNumber, setConfirmationNumber] = useState('')
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!productId) return
    fetch(`/api/medusa/store/products/${productId}?fields=*variants`)
      .then(r => r.json())
      .then(d => { setService(d.product ?? null); setLoadingSvc(false) })
      .catch(() => setLoadingSvc(false))
  }, [productId])

  // Fetch booked slots whenever date changes
  useEffect(() => {
    if (!form.date || !productId) return
    setLoadingSlots(true)
    setForm(f => ({ ...f, time: '' }))
    fetch(`/api/medusa/store/appointments?service_id=${productId}&date=${form.date}`)
      .then(r => r.json())
      .then(d => { setBookedSlots(d.booked_slots ?? []); setLoadingSlots(false) })
      .catch(() => setLoadingSlots(false))
  }, [form.date, productId])

  const price = service?.variants?.[0]?.prices?.[0]
  const today = new Date().toISOString().split('T')[0]

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.time) { setError('Please select a time slot.'); return }
    setSubmitting(true)
    setError('')
    try {
      const res = await fetch('/api/medusa/store/appointments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          service_id: productId,
          appointment_date: form.date,
          appointment_time: form.time,
          service_name: service?.title || 'Appointment',
          customer_name: form.name,
          customer_phone: form.phone,
          customer_email: form.email || null,
          notes: form.notes || null,
        }),
        signal: AbortSignal.timeout(15000),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Booking failed')
      setConfirmationNumber(data.confirmation_number ?? '')
      setSuccess(true)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Something went wrong. Please try again or call us directly.')
    }
    setSubmitting(false)
  }

  if (loadingSvc) return <div className="min-h-screen flex items-center justify-center bg-background"><Loader2 className="h-10 w-10 animate-spin text-primary" /></div>
  if (!service) return <div className="min-h-screen flex items-center justify-center bg-background"><p className="text-muted-foreground mr-4">Service not found.</p><Link href="/services" className="text-primary hover:underline">Back to Services</Link></div>

  if (success) return (
    <main className="min-h-screen bg-background flex items-center justify-center p-4">
      <div className="max-w-md w-full text-center">
        <div className="bg-card border border-border rounded-2xl p-10">
          <CircleCheck className="h-16 w-16 text-green-500 mx-auto mb-4" />
          <h1 className="text-2xl font-bold mb-1">Appointment Booked!</h1>
          <p className="font-semibold mb-1">{service.title}</p>
          <p className="text-muted-foreground text-sm mb-1">{form.date} at {form.time}</p>
          {confirmationNumber && <p className="text-xs font-mono bg-muted text-muted-foreground rounded-lg px-3 py-1.5 inline-block mt-3 mb-2">{confirmationNumber}</p>}
          <p className="text-sm text-muted-foreground mt-3 mb-8">We will confirm your appointment via phone shortly.</p>
          <Link href="/services" className="bg-primary text-primary-foreground px-8 py-3 rounded-lg hover:bg-primary/90 transition-colors font-medium inline-block">Browse More Services</Link>
        </div>
      </div>
    </main>
  )

  return (
    <main className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-10 max-w-4xl">
        <Link href="/services" className="inline-flex items-center gap-2 text-muted-foreground hover:text-foreground mb-8 transition-colors text-sm">
          <ArrowLeft className="h-4 w-4" />Back to Services
        </Link>
        <div className="grid lg:grid-cols-2 gap-10">
          <div>
            {service.thumbnail && (
              <div className="relative aspect-[4/3] rounded-2xl overflow-hidden bg-muted mb-5">
                <Image src={service.thumbnail} alt={service.title} fill sizes="(max-width: 1024px) 100vw, 50vw" className="object-cover" />
              </div>
            )}
            <h1 className="text-2xl font-bold mb-3">{service.title}</h1>
            {service.description && <p className="text-muted-foreground leading-relaxed mb-4">{service.description}</p>}
            {price && <p className="text-3xl font-bold text-primary">{formatPrice(price.amount, price.currency_code)}</p>}
          </div>
          <div>
            <div className="bg-card border border-border rounded-2xl p-6 sticky top-6">
              <h2 className="text-xl font-semibold mb-5 flex items-center gap-2">
                <CalendarCheck className="h-5 w-5 text-primary" />Book an Appointment
              </h2>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-xs font-medium mb-1 text-muted-foreground uppercase tracking-wide">Date *</label>
                  <input required type="date" min={today} value={form.date}
                    onChange={e => setForm(f => ({...f, date: e.target.value}))}
                    className="w-full border border-border rounded-lg px-3 py-2 bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary" />
                </div>
                {form.date && (
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <label className="block text-xs font-medium text-muted-foreground uppercase tracking-wide">Time *</label>
                      {loadingSlots && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />}
                    </div>
                    <div className="grid grid-cols-3 gap-2">
                      {TIME_SLOTS.map(slot => {
                        const booked = bookedSlots.includes(slot)
                        const selected = form.time === slot
                        return (
                          <button key={slot} type="button" disabled={booked}
                            onClick={() => !booked && setForm(f => ({...f, time: slot}))}
                            className={`py-2 rounded-lg text-sm font-medium border transition-all ${
                              booked ? 'bg-muted text-muted-foreground/40 border-border cursor-not-allowed line-through'
                              : selected ? 'bg-primary text-primary-foreground border-primary'
                              : 'bg-background text-foreground border-border hover:border-primary hover:text-primary'
                            }`}>
                            {slot}
                          </button>
                        )
                      })}
                    </div>
                  </div>
                )}
                <div className="border-t border-border pt-4 space-y-3">
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground uppercase tracking-wide">Full Name *</label>
                    <input required type="text" value={form.name} onChange={e => setForm(f => ({...f, name: e.target.value}))}
                      className="w-full border border-border rounded-lg px-3 py-2 bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary" />
                  </div>
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground uppercase tracking-wide">Phone *</label>
                    <input required type="tel" value={form.phone} onChange={e => setForm(f => ({...f, phone: e.target.value}))}
                      placeholder="+27 " className="w-full border border-border rounded-lg px-3 py-2 bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary" />
                  </div>
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground uppercase tracking-wide">Email</label>
                    <input type="email" value={form.email} onChange={e => setForm(f => ({...f, email: e.target.value}))}
                      className="w-full border border-border rounded-lg px-3 py-2 bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary" />
                  </div>
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground uppercase tracking-wide">Notes</label>
                    <textarea rows={2} value={form.notes} onChange={e => setForm(f => ({...f, notes: e.target.value}))}
                      className="w-full border border-border rounded-lg px-3 py-2 bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none" />
                  </div>
                </div>
                {error && <p className="text-destructive text-sm">{error}</p>}
                <button type="submit" disabled={submitting || !form.time}
                  className="w-full bg-primary text-primary-foreground py-3 rounded-lg hover:bg-primary/90 transition-colors font-semibold disabled:opacity-50">
                  {submitting ? 'Booking…' : 'Confirm Appointment'}
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </main>
  )
}
