import { fetchAllProducts } from '@/lib/stripe/products'
import { ProductGrid } from '@/components/product-grid'
import Link from 'next/link'

export const metadata = {
  title: 'Products | Rocky Mountain Vending',
  description: 'Shop our selection of vending machines and equipment',
}

export default async function ProductsPage() {
  let products = []
  let error: string | null = null

  try {
    products = await fetchAllProducts()
  } catch (err) {
    console.error('Error fetching products:', err)
    if (err instanceof Error) {
      if (err.message.includes('STRIPE_SECRET_KEY')) {
        error = 'Stripe configuration error. Please check environment variables.'
      } else {
        error = 'Failed to load products. Please try again later.'
      }
    } else {
      error = 'Failed to load products. Please try again later.'
    }
  }

  return (
    <div className="container mx-auto px-4 py-8 md:py-16">
      <div className="text-center mb-12 md:mb-16 relative">
        <div className="absolute top-0 right-0">
          <Link 
            href="/stripe-setup" 
            className="text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            Admin: Setup Guide
          </Link>
        </div>
        <h1 className="text-3xl font-bold tracking-tight md:text-4xl lg:text-5xl mb-4 text-balance">
          Our Products
        </h1>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto text-pretty leading-relaxed">
          Browse our selection of vending machines and equipment
        </p>
      </div>

      {error ? (
        <div className="text-center py-12">
          <p className="text-destructive">{error}</p>
          <p className="text-sm text-muted-foreground mt-2">
            Please try again later.
          </p>
        </div>
      ) : products.length === 0 ? (
        <div className="text-center py-12">
          <div className="mb-6">
            <p className="text-lg font-medium mb-2">
              No products available yet
            </p>
            <p className="text-muted-foreground">
              Our product catalog is being prepared. Please check back soon or contact us directly for current offerings.
            </p>
          </div>
          <div className="max-w-md mx-auto text-sm text-muted-foreground bg-muted/50 p-4 rounded-lg">
            <p className="font-medium mb-1">For Vending Machine Sales:</p>
            <p>Call us at (435) 233-9668 or visit our contact page for immediate assistance.</p>
          </div>
        </div>
      ) : (
        <ProductGrid products={products} />
      )}
    </div>
  )
}

