'use client'
import { useState, useEffect } from 'react'
import { useMedusaProducts } from '@/hooks/useMedusaProducts'
import Image from 'next/image'
import Link from 'next/link'
import { BedDouble } 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)}`
}

interface Category { id: string; name: string }

export default function RoomsPage() {
  const { products: rooms, loading, error } = useMedusaProducts(50)
  const [categories, setCategories] = useState<Category[]>([])
  const [activeCategory, setActiveCategory] = useState<string | null>(null)

  useEffect(() => {
    fetch('/api/medusa/store/product-categories?limit=20', {
      headers: { 'x-publishable-api-key': process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || '' },
    })
      .then(r => r.json())
      .then(d => setCategories(d.product_categories || []))
      .catch(() => {})
  }, [])

  const filtered = activeCategory
    ? rooms.filter(r => (r as any).categories?.some((c: any) => c.id === activeCategory))
    : rooms

  if (loading) return <div className="min-h-screen flex items-center justify-center"><div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" /></div>
  if (error) return <div className="min-h-screen flex items-center justify-center"><p className="text-destructive">Failed to load rooms.</p></div>

  return (
    <main className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-12">
        <h1 className="text-3xl font-bold mb-8">Our Rooms</h1>
        {categories.length > 0 && (
          <div className="flex gap-2 flex-wrap mb-8">
            <button onClick={() => setActiveCategory(null)} className={"px-4 py-2 rounded-full text-sm font-medium transition-colors " + (activeCategory === null ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-accent")}>All</button>
            {categories.map(cat => (
              <button key={cat.id} onClick={() => setActiveCategory(cat.id)} className={"px-4 py-2 rounded-full text-sm font-medium transition-colors " + (activeCategory === cat.id ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-accent")}>{cat.name}</button>
            ))}
          </div>
        )}
        {filtered.length === 0 ? (
          <div className="text-center py-20">
            <BedDouble className="h-16 w-16 mx-auto mb-4 text-muted-foreground/40" />
            <p className="text-muted-foreground">No rooms available.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filtered.map((room) => {
              const variant = room.variants?.[0]
              const price = variant?.prices?.[0]
              return (
                <div key={room.id} className="bg-card rounded-xl overflow-hidden border border-border hover:shadow-lg transition-all">
                  {room.thumbnail && (
                    <div className="relative aspect-video overflow-hidden bg-muted">
                      <Image src={room.thumbnail} alt={room.title} fill sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw" className="object-cover" />
                    </div>
                  )}
                  <div className="p-5">
                    <h2 className="text-xl font-semibold mb-2">{room.title}</h2>
                    {room.description && <p className="text-muted-foreground text-sm mb-4">{room.description}</p>}
                    {price && <p className="text-2xl font-bold text-primary mb-4">{formatPrice(price.amount, price.currency_code)}<span className="text-sm font-normal text-muted-foreground">/night</span></p>}
                    <Link href={"/booking/" + room.id} className="block w-full bg-primary text-primary-foreground py-2 rounded-lg hover:bg-primary/90 transition-colors font-medium text-center">Book This Room</Link>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>
    </main>
  )
}
