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

export default function ServicesPage() {
  const { products: services, loading, error } = useProducts(100)
  const [activeCollection, setActiveCollection] = useState<string>('All')

  const collections = useMemo(() => Array.from(
    new Map(services.flatMap(s => s.collection ? [[s.collection.id, s.collection]] : [])).values()
  ), [services])

  const filtered = useMemo(() => {
    if (activeCollection === 'All') return services
    return services.filter(s => s.collection?.id === activeCollection)
  }, [services, activeCollection])

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <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 bg-background">
        <p className="text-destructive">Failed to load services. Please try again.</p>
      </div>
    )
  }

  return (
    <main className="min-h-screen bg-background">
      {/* Page header */}
      <div className="bg-card border-b border-border">
        <div className="container mx-auto px-4 py-10">
          <Link href="/" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground mb-4 transition-colors">
            <ArrowLeft className="h-4 w-4" />
            Back to home
          </Link>
          <h1 className="text-4xl font-bold tracking-tight">Our Services</h1>
          {services.length > 0 && (
            <p className="text-muted-foreground mt-1">{services.length} service{services.length !== 1 ? 's' : ''} available</p>
          )}
        </div>
      </div>

      <div className="container mx-auto px-4 py-10">
        {/* Collection filter tabs */}
        {collections.length > 0 && (
          <div className="flex gap-2 flex-wrap mb-8">
            {[{ id: 'All', title: 'All' }, ...collections].map(col => (
              <button
                key={col.id}
                onClick={() => setActiveCollection(col.id)}
                className={"px-4 py-2 rounded-full text-sm font-medium transition-colors " + (activeCollection === col.id ? "bg-primary text-primary-foreground shadow-sm" : "bg-muted text-muted-foreground hover:bg-accent hover:text-accent-foreground")}
              >
                {col.title ?? col.id}
              </button>
            ))}
          </div>
        )}

        {/* Services grid */}
        {filtered.length === 0 ? (
          <div className="text-center py-24">
            <Sparkles className="h-14 w-14 mx-auto mb-4 text-muted-foreground/30" />
            <p className="text-muted-foreground text-lg">
              {activeCollection !== 'All' ? 'No services in this category.' : 'Services coming soon.'}
            </p>
            {activeCollection !== 'All' && (
              <button onClick={() => setActiveCollection('All')} className="mt-3 text-sm text-primary hover:underline">
                View all services
              </button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filtered.map((service) => {
              const variant = service.variants?.[0]
              const price = variant?.prices?.[0]
              const amount = price?.amount
              const currency = price?.currency_code
              return (
                <div key={service.id} className="bg-card rounded-2xl overflow-hidden border border-border hover:shadow-lg hover:-translate-y-0.5 transition-all duration-200 flex flex-col">
                  {service.thumbnail && (
                    <div className="relative aspect-video overflow-hidden bg-muted shrink-0">
                      <Image src={service.thumbnail} alt={service.title} fill sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw" className="object-cover" />
                    </div>
                  )}
                  <div className="p-5 flex flex-col flex-1">
                    {service.collection?.title && (
                      <span className="text-xs font-medium text-primary/70 uppercase tracking-wide mb-1">{service.collection.title}</span>
                    )}
                    <h2 className="text-lg font-semibold leading-snug mb-1">{service.title}</h2>
                    {service.description && (
                      <p className="text-muted-foreground text-sm leading-relaxed mb-3 flex-1 line-clamp-2">{service.description}</p>
                    )}
                    <div className="flex items-center justify-between mt-auto pt-3 border-t border-border">
                      {amount !== undefined ? (
                        <p className="text-xl font-bold text-primary">{formatPrice(amount, currency)}</p>
                      ) : (
                        <p className="text-sm text-muted-foreground">Price on request</p>
                      )}
                      <Link
                        href={"/booking/" + service.id}
                        className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors"
                      >
                        Book Now
                      </Link>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>
    </main>
  )
}
