<template>
  <div class="container mx-auto px-4 py-8">
    <LoadingErrorState
      :is-loading="!isMarketReady && ((marketStore.isLoading ?? false) || marketPreloader.isPreloading.value)"
      :loading-message="marketPreloader.isPreloading.value ? 'Preloading market...' : 'Loading market...'"
      :has-error="!!(marketStore.error || marketPreloader.preloadError.value) && !isMarketReady"
      error-title="Failed to load market"
      :error-message="marketStore.error || marketPreloader.preloadError.value || ''"
      @retry="retryLoadMarket"
    >
      <!-- Market Header - Optimized for Mobile -->
      <div class="mb-4 sm:mb-6 lg:mb-8">
        <!-- Market Info and Search - Responsive Layout -->
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-3 sm:gap-4 lg:gap-6">
          <!-- Market Info - Compact on Mobile -->
          <div class="flex items-center space-x-3 sm:space-x-4">
            <Avatar v-if="marketStore.activeMarket?.opts?.logo" class="h-10 w-10 sm:h-12 sm:w-12">
              <AvatarImage :src="marketStore.activeMarket.opts.logo" />
              <AvatarFallback>M</AvatarFallback>
            </Avatar>
            <div>
              <h1 class="text-xl sm:text-2xl lg:text-3xl font-bold">
                {{ marketStore.activeMarket?.opts?.name || 'Market' }}
              </h1>
              <p v-if="marketStore.activeMarket?.opts?.description" class="text-muted-foreground text-xs sm:text-sm lg:text-base line-clamp-1 sm:line-clamp-2">
                {{ marketStore.activeMarket.opts.description }}
              </p>
            </div>
          </div>

          <!-- Enhanced Search Bar - Full Width on Mobile -->
          <div class="w-full lg:flex-1 lg:max-w-md">
            <MarketSearchBar
              :data="marketStore.products as Product[]"
              :options="searchOptions"
              :show-enhancements="true"
              @results="handleSearchResults"
              @filter-category="handleCategoryFilter"
              class="w-full"
            />
          </div>
        </div>
      </div>



      <!-- Enhanced Category Filters -->
      <CategoryFilterBar
        :categories="allCategories"
        :selected-count="selectedCategoriesCount"
        :filter-mode="filterMode"
        :product-count="productsToDisplay.length"
        @toggle-category="toggleCategory"
        @clear-all="clearAllCategoryFilters"
        @set-filter-mode="setFilterMode"
      />

      <!-- Product Grid with Loading and Empty States -->
      <ProductGrid
        v-if="isMarketReady"
        :products="productsToDisplay as Product[]"
        :is-loading="marketStore.isLoading ?? false"
        loading-message="Loading products..."
        empty-title="No products found"
        empty-message="Try adjusting your search or filters"
        @add-to-cart="addToCart"
        @view-stall="viewStall"
      />

    <!-- Cart Summary -->
    <CartButton />

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

<script setup lang="ts">
import { onMounted, onUnmounted, computed, ref } 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 { useCategoryFilter } from '../composables/useCategoryFilter'
import { config } from '@/lib/config'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import MarketSearchBar from '../components/MarketSearchBar.vue'
import ProductGrid from '../components/ProductGrid.vue'
import CategoryFilterBar from '../components/CategoryFilterBar.vue'
import CartButton from '../components/CartButton.vue'
import LoadingErrorState from '../components/LoadingErrorState.vue'
import type { Product } from '../types/market'
import type { FuzzySearchOptions } from '@/composables/useFuzzySearch'

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

// Dynamic category filtering: use search results when available, otherwise all products
const productsForCategoryFilter = computed(() => {
  return searchResults.value.length > 0
    ? searchResults.value
    : (marketStore.products as Product[])
})

// Category filtering with optimized composable
const {
  allCategories,
  selectedCount: selectedCategoriesCount,
  selectedCategoryNames: selectedCategories,
  hasActiveFilters,
  filterMode,
  toggleCategory,
  clearAllCategories: clearAllCategoryFilters,
  setFilterMode
} = useCategoryFilter(productsForCategoryFilter)

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

// Fuzzy search state
const searchResults = ref<Product[]>([])


// Fuzzy search configuration for products and stalls
const searchOptions: FuzzySearchOptions<Product> = {
  fuseOptions: {
    keys: [
      { name: 'name', weight: 0.7 },         // Product name has highest weight
      { name: 'stallName', weight: 0.5 },    // Stall name is important for discovery
      { name: 'description', weight: 0.3 },  // Description provides context
      { name: 'categories', weight: 0.4 }    // Categories help with discovery
    ],
    threshold: 0.4,        // More tolerant of typos (0.0 = perfect match, 1.0 = match anything)
    ignoreLocation: true,  // Don't care about where in the string the match is
    findAllMatches: true,  // Find all matches, not just the first
    minMatchCharLength: 2, // Minimum length of a matched character sequence
    shouldSort: true       // Sort results by score
  },
  resultLimit: 50,         // Limit results for performance
  minSearchLength: 2,      // Start searching after 2 characters
  matchAllWhenSearchEmpty: true
}

// 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 hasError = !!(marketStore.error || marketPreloader.preloadError.value)

  // Market is ready if:
  // 1. Successfully preloaded, OR
  // 2. Has products, not loading, and no current errors
  const ready = marketPreloader.isPreloaded.value ||
         (marketStore.products.length > 0 && !isLoading && !hasError)

  return ready
})

// Products to display (combines search results with category filtering)
const productsToDisplay = computed(() => {
  // Start with either search results or all products
  const baseProducts = searchResults.value.length > 0
    ? searchResults.value
    : marketStore.products

  // Apply category filtering using our composable's proper AND/OR logic
  if (!hasActiveFilters.value) {
    return baseProducts
  }

  // Use the composable's filtering logic which supports AND/OR modes
  return baseProducts.filter(product => {
    if (!product.categories?.length) return false

    // Normalize product categories
    const productCategories = product.categories
      .filter(cat => cat && cat.trim())
      .map(cat => cat.toLowerCase())

    if (productCategories.length === 0) return false

    // Count matches between product categories and selected categories
    const matchingCategories = productCategories.filter(cat =>
      selectedCategories.value.includes(cat)
    )

    // Apply AND/OR logic based on filter mode
    if (filterMode.value === 'all') {
      // AND logic: Product must have ALL selected categories
      return matchingCategories.length === selectedCategories.value.length
    } else {
      // OR logic: Product must have ANY selected category
      return matchingCategories.length > 0
    }
  })
})

const loadMarket = async () => {
  try {
    // TODO: Determine if we need naddr for market configuration
    // Currently bypassing naddr requirement as it may not be needed
    // Consider using naddr only for nostr-related configuration
    // Original code: const naddr = config.market.defaultNaddr
    // if (!naddr) throw new Error('No market naddr configured')

    await market.connectToMarket()

    // Load market with naddr if available, otherwise load default market
    const naddr = config.market.defaultNaddr
    if (naddr) {
      await market.loadMarket(naddr)
    } else {
      // Load market without specific naddr - uses default market data
      await market.loadMarket('')
    }
    
    // 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: Product, quantity?: number) => {
  marketStore.addToStallCart(product, quantity || 1)
}

const viewStall = (stallId: string) => {
  // Navigate to the stall view page
  router.push(`/market/stall/${stallId}`)
}

// Handle fuzzy search results
const handleSearchResults = (results: Product[]) => {
  searchResults.value = results
}

// Handle category filtering from fuzzy search
const handleCategoryFilter = (category: string) => {
  toggleCategory(category)
}

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> 
