<template>
  <div class="product-grid-container">
    <LoadingErrorState
      :is-loading="isLoading"
      :loading-message="loadingMessage"
      :has-error="false"
      :full-height="false"
    >
      <!-- Empty State -->
      <div v-if="products.length === 0" class="text-center py-12">
        <slot name="empty">
          <EmptyIcon class="w-24 h-24 text-muted-foreground/50 mx-auto mb-4" />
          <h3 class="text-xl font-semibold text-gray-600 mb-2">{{ emptyTitle }}</h3>
          <p class="text-gray-500">{{ emptyMessage }}</p>
        </slot>
      </div>

      <!-- Product Grid -->
      <div v-else :class="gridClasses">
      <ProductCard
        v-for="product in products"
        :key="product.id"
        :product="product as Product"
        @add-to-cart="handleAddToCart"
        @view-details="handleViewDetails"
        @view-stall="$emit('view-stall', $event)"
      />
      </div>

    </LoadingErrorState>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { Package as EmptyIcon } from 'lucide-vue-next'
import ProductCard from './ProductCard.vue'
import LoadingErrorState from './LoadingErrorState.vue'
import type { Product } from '../types/market'

interface Props {
  products: Product[]
  isLoading?: boolean
  loadingMessage?: string
  emptyTitle?: string
  emptyMessage?: string
  columns?: {
    mobile?: number
    sm?: number
    md?: number
    lg?: number
    xl?: number
  }
}

const props = withDefaults(defineProps<Props>(), {
  isLoading: false,
  loadingMessage: 'Loading products...',
  emptyTitle: 'No products found',
  emptyMessage: 'Try adjusting your filters or search terms',
  columns: () => ({
    mobile: 1,
    sm: 2,
    md: 2,
    lg: 3,
    xl: 4
  })
})

const emit = defineEmits<{
  'add-to-cart': [product: Product, quantity?: number]
  'view-stall': [stallId: string]
}>()

// Compute grid classes based on column configuration
const gridClasses = computed(() => {
  const cols = props.columns
  const classes = ['grid', 'gap-6']

  // Mobile columns
  if (cols.mobile === 1) classes.push('grid-cols-1')
  else if (cols.mobile === 2) classes.push('grid-cols-2')

  // Responsive columns
  if (cols.sm) classes.push(`sm:grid-cols-${cols.sm}`)
  if (cols.md) classes.push(`md:grid-cols-${cols.md}`)
  if (cols.lg) classes.push(`lg:grid-cols-${cols.lg}`)
  if (cols.xl) classes.push(`xl:grid-cols-${cols.xl}`)

  return classes.join(' ')
})

const router = useRouter()

// Handle view details by navigating to product page
const handleViewDetails = (product: Product) => {
  router.push(`/market/product/${product.id}`)
}

// Handle add to cart from product card (quick add, quantity 1)
const handleAddToCart = (product: Product) => {
  emit('add-to-cart', product, 1)
}
</script>