'use client'
import { useState, useEffect, Suspense } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import Image from 'next/image'
import Link from 'next/link'
import { Search, BedDouble, CheckCircle, XCircle, Loader2, ArrowRight } from 'lucide-react'

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)}`
}

function calcNights(checkIn: string, checkOut: string) {
  if (!checkIn || !checkOut) return 0
  return Math.max(0, Math.round((new Date(checkOut).getTime() - new Date(checkIn).getTime()) / 86400000))
}

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

function RoomCard({ room, checkIn, checkOut, guests, nights }: { room: SearchRoom; checkIn: string; checkOut: string; guests: string; nights: number }) {
  const [avail, setAvail] = useState<{ available: boolean | null; loading: boolean }>({ available: null, loading: false })
  const price = room.variants?.[0]?.prices?.[0]
  const nightly = price?.amount ?? 0
  const total = nightly * nights

  useEffect(() => {
    if (!checkIn || !checkOut || nights === 0) { setAvail({ available: null, loading: false }); return }
    setAvail({ available: null, loading: true })
    const qs = new URLSearchParams({ room_type: room.id, check_in: checkIn, check_out: checkOut }).toString()
    fetch(`/api/medusa/store/hotel/bookings?${qs}`)
      .then(r => r.json())
      .then(d => setAvail({ available: d.available ?? null, loading: false }))
      .catch(() => setAvail({ available: null, loading: false }))
  }, [room.id, checkIn, checkOut, nights])

  const unavailable = avail.available === false
  const href = `/booking/${room.id}?checkIn=${checkIn}&checkOut=${checkOut}&guests=${guests}`

  return (
    <div className="bg-card rounded-2xl border border-border overflow-hidden hover:shadow-lg transition-all group">
      {room.thumbnail && (
        <div className="relative aspect-video overflow-hidden bg-muted">
          <Image src={room.thumbnail} alt={room.title} fill sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw" className="object-cover group-hover:scale-105 transition-transform duration-300" />
        </div>
      )}
      <div className="p-5">
        <div className="flex items-start justify-between gap-3 mb-2">
          <h2 className="text-lg font-semibold leading-tight">{room.title}</h2>
          {avail.loading && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground shrink-0 mt-0.5" />}
          {!avail.loading && avail.available === true && <CheckCircle className="h-4 w-4 text-green-500 shrink-0 mt-0.5" />}
          {!avail.loading && avail.available === false && <XCircle className="h-4 w-4 text-red-500 shrink-0 mt-0.5" />}
        </div>
        {room.description && <p className="text-muted-foreground text-sm mb-4 line-clamp-2">{room.description}</p>}
        <div className="flex items-end justify-between mb-4">
          <div>
            {nightly > 0 && <p className="text-xl font-bold text-primary">{formatPrice(nightly, price?.currency_code)}<span className="text-sm font-normal text-muted-foreground">/night</span></p>}
            {nights > 0 && total > 0 && <p className="text-xs text-muted-foreground mt-0.5">{nights} night{nights !== 1 ? 's' : ''} = {formatPrice(total, price?.currency_code)} total</p>}
          </div>
          {avail.available === true && <span className="text-xs bg-green-50 text-green-700 border border-green-200 px-2 py-0.5 rounded-full">Available</span>}
          {avail.available === false && <span className="text-xs bg-red-50 text-red-600 border border-red-200 px-2 py-0.5 rounded-full">Unavailable</span>}
        </div>
        <Link
          href={unavailable ? '#' : href}
          aria-disabled={unavailable}
          className={"flex items-center justify-center gap-1.5 w-full py-2.5 rounded-xl font-medium text-sm transition-all " + (unavailable ? "bg-muted text-muted-foreground cursor-not-allowed pointer-events-none" : "bg-primary text-primary-foreground hover:bg-primary/90")}
        >
          {unavailable ? 'Not Available' : 'Select Room'}
          {!unavailable && <ArrowRight className="h-3.5 w-3.5" />}
        </Link>
      </div>
    </div>
  )
}

function BookingSearchContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const today = new Date().toISOString().split('T')[0]
  const tomorrow = new Date(Date.now() + 86400000).toISOString().split('T')[0]

  const [checkIn, setCheckIn]   = useState(searchParams.get('checkIn') || today)
  const [checkOut, setCheckOut] = useState(searchParams.get('checkOut') || tomorrow)
  const [guests, setGuests]     = useState(searchParams.get('guests') || '2')
  const [rooms, setRooms]       = useState<SearchRoom[]>([])
  const [loading, setLoading]   = useState(true)

  const nights = calcNights(checkIn, checkOut)

  useEffect(() => {
    fetch('/api/medusa/products?limit=50')
      .then(r => r.json())
      .then(d => { setRooms(d.products ?? []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  function handleSearch(e: React.FormEvent) {
    e.preventDefault()
    router.push(`/booking?checkIn=${checkIn}&checkOut=${checkOut}&guests=${guests}`)
  }

  return (
    <main className="min-h-screen bg-background">
      <div className="bg-card border-b border-border sticky top-0 z-10 shadow-sm">
        <div className="container mx-auto px-4 py-4">
          <form onSubmit={handleSearch} className="flex flex-wrap gap-3 items-end">
            <div className="flex-1 min-w-[130px]">
              <label className="block text-xs font-medium text-muted-foreground mb-1 uppercase tracking-wide">Check-in</label>
              <input type="date" value={checkIn} min={today} onChange={e => setCheckIn(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 className="flex-1 min-w-[130px]">
              <label className="block text-xs font-medium text-muted-foreground mb-1 uppercase tracking-wide">Check-out</label>
              <input type="date" value={checkOut} min={checkIn} onChange={e => setCheckOut(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 className="w-24">
              <label className="block text-xs font-medium text-muted-foreground mb-1 uppercase tracking-wide">Guests</label>
              <select value={guests} onChange={e => setGuests(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">
                {[1,2,3,4,5,6,7,8].map(n => <option key={n} value={n}>{n}</option>)}
              </select>
            </div>
            <button type="submit" className="bg-primary text-primary-foreground px-5 py-2.5 rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors flex items-center gap-2">
              <Search className="h-4 w-4" />Update
            </button>
          </form>
          {nights > 0 && (
            <p className="text-xs text-muted-foreground mt-2">
              {nights} night{nights !== 1 ? 's' : ''} · {guests} guest{Number(guests) !== 1 ? 's' : ''} · Checking availability…
            </p>
          )}
        </div>
      </div>
      <div className="container mx-auto px-4 py-8">
        {loading ? (
          <div className="flex items-center justify-center py-24"><Loader2 className="h-10 w-10 animate-spin text-primary" /></div>
        ) : rooms.length === 0 ? (
          <div className="text-center py-24">
            <BedDouble className="h-16 w-16 mx-auto mb-4 text-muted-foreground/30" />
            <p className="text-lg font-medium mb-2">No rooms available</p>
            <p className="text-muted-foreground text-sm">Please contact us directly to check availability.</p>
          </div>
        ) : (
          <>
            <p className="text-sm text-muted-foreground mb-6">{rooms.length} room{rooms.length !== 1 ? 's' : ''} · {nights > 0 ? `${nights} night${nights !== 1 ? 's' : ''}` : 'Select dates above'}</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {rooms.map(room => (
                <RoomCard key={room.id} room={room} checkIn={checkIn} checkOut={checkOut} guests={guests} nights={nights} />
              ))}
            </div>
          </>
        )}
      </div>
    </main>
  )
}

export default function BookingSearchPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center"><Loader2 className="h-10 w-10 animate-spin text-primary" /></div>}>
      <BookingSearchContent />
    </Suspense>
  )
}
