<template>
  <div class="container mx-auto px-4 py-8">
    <!-- Loading State -->
    <div v-if="!isMarketReady && ((marketStore.isLoading ?? false) || marketPreloader.isPreloading)" class="flex justify-center items-center min-h-64">
      <div class="flex flex-col items-center space-y-4">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <p class="text-gray-600">
          {{ marketPreloader.isPreloading ? 'Preloading market...' : 'Loading market...' }}
        </p>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="(marketStore.error || marketPreloader.preloadError) && marketStore.products.length === 0" class="flex justify-center items-center min-h-64">
      <div class="text-center">
        <h2 class="text-2xl font-bold text-red-600 mb-4">Failed to load market</h2>
        <p class="text-gray-600 mb-4">{{ marketStore.error || marketPreloader.preloadError }}</p>
        <Button @click="retryLoadMarket" variant="outline">
          Try Again
        </Button>
      </div>
    </div>

    <!-- Market Content -->
    <div v-else>
      <!-- Market Header -->
      <div class="flex items-center justify-between mb-8">
        <div class="flex items-center space-x-4">
          <Avatar v-if="marketStore.activeMarket?.opts?.logo">
            <AvatarImage :src="marketStore.activeMarket.opts.logo" />
            <AvatarFallback>M</AvatarFallback>
          </Avatar>
          <div>
            <h1 class="text-3xl font-bold">
              {{ marketStore.activeMarket?.opts?.name || 'Market' }}
            </h1>
            <p v-if="marketStore.activeMarket?.opts?.description" class="text-gray-600">
              {{ marketStore.activeMarket.opts.description }}
            </p>
          </div>
        </div>
        
        <!-- Search Bar -->
        <div class="flex-1 max-w-md ml-8">
          <Input
            v-model="marketStore.searchText"
            type="text"
            placeholder="Search products..."
            class="w-full"
          />
        </div>
      </div>

      <!-- Category Filters -->
      <div v-if="marketStore.allCategories.length > 0" class="mb-6">
        <div class="flex flex-wrap gap-2">
          <Badge
            v-for="category in marketStore.allCategories"
            :key="category.category"
            :variant="category.selected ? 'default' : 'secondary'"
            class="cursor-pointer hover:bg-blue-100"
            @click="marketStore.toggleCategoryFilter(category.category)"
          >
            {{ category.category }}
            <span class="ml-1 text-xs">({{ category.count }})</span>
          </Badge>
        </div>
      </div>

      <!-- No Products State -->
      <div v-if="isMarketReady && marketStore.filteredProducts.length === 0 && !(marketStore.isLoading ?? false)" class="text-center py-12">
        <h3 class="text-xl font-semibold text-gray-600 mb-2">No products found</h3>
        <p class="text-gray-500">Try adjusting your search or filters</p>
      </div>

      <!-- Product Grid -->
      <div v-if="isMarketReady && marketStore.filteredProducts.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <ProductCard
          v-for="product in marketStore.filteredProducts"
          :key="product.id"
          :product="product"
          @add-to-cart="addToCart"
          @view-details="viewProduct"
        />
      </div>

      <!-- Cart Summary -->
      <div v-if="marketStore.totalCartItems > 0" class="fixed bottom-4 right-4">
        <Button @click="viewCart" class="shadow-lg">
          <ShoppingCart class="w-5 h-5 mr-2" />
          Cart ({{ marketStore.totalCartItems }})
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMarketStore } from '@/modules/market/stores/market'
import { useMarket } from '../composables/useMarket'
import { useMarketPreloader } from '../composables/useMarketPreloader'
import { config } from '@/lib/config'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { ShoppingCart } from 'lucide-vue-next'
import ProductCard from '../components/ProductCard.vue'

const router = useRouter()
const marketStore = useMarketStore()
const market = useMarket()
const marketPreloader = useMarketPreloader()

let unsubscribe: (() => void) | null = null

// Check if we need to load market data
const needsToLoadMarket = computed(() => {
  return !marketPreloader.isPreloaded.value && 
         !marketPreloader.isPreloading.value && 
         marketStore.products.length === 0
})

// Check if market data is ready (either preloaded or loaded)
const isMarketReady = computed(() => {
  const isLoading = marketStore.isLoading ?? false
  const ready = marketPreloader.isPreloaded.value || 
         (marketStore.products.length > 0 && !isLoading)
  
  return ready
})

const loadMarket = async () => {
  try {
    const naddr = config.market.defaultNaddr
    if (!naddr) {
      throw new Error('No market naddr configured')
    }

    await market.connectToMarket()
    await market.loadMarket(naddr)
    
    // Subscribe to real-time updates
    unsubscribe = market.subscribeToMarketUpdates()
    
  } catch (error) {
    marketStore.setError(error instanceof Error ? error.message : 'Failed to load market')
  }
}

const retryLoadMarket = () => {
  marketStore.setError(null)
  marketPreloader.resetPreload()
  loadMarket()
}

const addToCart = (product: any) => {
  marketStore.addToCart(product)
}

const viewProduct = (_product: any) => {
  // TODO: Navigate to product detail page
}

const viewCart = () => {
  router.push('/cart')
}

onMounted(() => {
  // Only load market if it hasn't been preloaded
  if (needsToLoadMarket.value) {
    loadMarket()
  } else if (marketPreloader.isPreloaded.value) {
    // Subscribe to real-time updates if market was preloaded
    unsubscribe = market.subscribeToMarketUpdates()
  }
})

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe()
  }
  market.disconnectFromMarket()
})
</script> 
