<template>
  <div class="bg-base-100 py-4 px-4 lg:px-6">
    <div class="flex items-center justify-center">
      <form
        @submit.prevent="handleSearch"
        class="flex items-center bg-base-100 rounded-full border border-base-300 shadow-sm hover:shadow-md transition-shadow"
      >
        <!-- Product field -->
        <div class="flex flex-col px-4 py-2 min-w-32 pl-6 rounded-l-full hover:bg-base-200/50 border-r border-base-300">
          <label class="text-xs font-semibold text-base-content/60 mb-0.5">
            {{ $t('search.product') }}
          </label>
          <div class="dropdown w-full">
            <input
              v-model="productQuery"
              type="text"
              :placeholder="$t('search.product_placeholder')"
              class="w-full bg-transparent outline-none text-sm"
              @focus="showProductDropdown = true"
              @input="filterProducts"
            />
            <ul
              v-if="showProductDropdown && filteredProducts.length > 0"
              class="dropdown-content menu bg-base-100 rounded-box z-50 w-64 max-h-60 overflow-auto p-2 shadow-lg border border-base-300 mt-2"
            >
              <li v-for="product in filteredProducts" :key="product.uuid">
                <a @click="selectProduct(product)">
                  {{ product.name }}
                  <span class="text-xs text-base-content/50">{{ product.categoryName }}</span>
                </a>
              </li>
            </ul>
          </div>
        </div>

        <!-- Quantity field -->
        <div class="flex flex-col px-4 py-2 min-w-32 hover:bg-base-200/50 border-r border-base-300">
          <label class="text-xs font-semibold text-base-content/60 mb-0.5">
            {{ $t('search.quantity') }}
          </label>
          <div class="flex items-center gap-1">
            <input
              v-model="quantity"
              type="number"
              min="1"
              :placeholder="$t('search.quantity_placeholder')"
              class="w-16 bg-transparent outline-none text-sm"
            />
            <select v-model="unit" class="bg-transparent outline-none text-sm text-base-content/70">
              <option value="t">{{ $t('units.t') }}</option>
              <option value="kg">{{ $t('units.kg') }}</option>
            </select>
          </div>
        </div>

        <!-- Destination field -->
        <div class="flex flex-col px-4 py-2 min-w-32 hover:bg-base-200/50">
          <label class="text-xs font-semibold text-base-content/60 mb-0.5">
            {{ $t('search.destination') }}
          </label>
          <div class="dropdown w-full">
            <input
              v-model="destinationQuery"
              type="text"
              :placeholder="$t('search.destination_placeholder')"
              class="w-full bg-transparent outline-none text-sm"
              @focus="showDestinationDropdown = true"
              @input="searchDestinations"
            />
            <ul
              v-if="showDestinationDropdown && destinations.length > 0"
              class="dropdown-content menu bg-base-100 rounded-box z-50 w-64 max-h-60 overflow-auto p-2 shadow-lg border border-base-300 mt-2"
            >
              <li v-for="dest in destinations" :key="dest.uuid">
                <a @click="selectDestination(dest)">
                  {{ dest.name }}
                  <span class="text-xs text-base-content/50">{{ dest.country }}</span>
                </a>
              </li>
            </ul>
          </div>
        </div>

        <!-- Search button -->
        <button
          type="submit"
          class="btn btn-primary btn-circle ml-2 mr-1"
          :disabled="!canSearch"
        >
          <Icon name="lucide:search" size="18" />
        </button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
const emit = defineEmits<{
  search: [params: { productUuid?: string; quantity?: number; unit?: string; destinationUuid?: string }]
}>()

const router = useRouter()
const localePath = useLocalePath()

// Product search
const productQuery = ref('')
const selectedProduct = ref<{ uuid: string; name: string; categoryName?: string } | null>(null)
const showProductDropdown = ref(false)
const allProducts = ref<Array<{ uuid: string; name: string; categoryName?: string }>>([])

const filteredProducts = computed(() => {
  if (!productQuery.value) return allProducts.value.slice(0, 10)
  const q = productQuery.value.toLowerCase()
  return allProducts.value.filter(p =>
    p.name.toLowerCase().includes(q) ||
    p.categoryName?.toLowerCase().includes(q)
  ).slice(0, 10)
})

const filterProducts = () => {
  showProductDropdown.value = true
}

const selectProduct = (product: typeof selectedProduct.value) => {
  selectedProduct.value = product
  productQuery.value = product?.name || ''
  showProductDropdown.value = false
}

// Quantity
const quantity = ref<number | undefined>()
const unit = ref('t')

// Destination search
const destinationQuery = ref('')
const selectedDestination = ref<{ uuid: string; name: string; country?: string } | null>(null)
const showDestinationDropdown = ref(false)
const destinations = ref<Array<{ uuid: string; name: string; country?: string }>>([])

const searchDestinations = async () => {
  showDestinationDropdown.value = true
  // TODO: implement destination search via GraphQL
}

const selectDestination = (dest: typeof selectedDestination.value) => {
  selectedDestination.value = dest
  destinationQuery.value = dest?.name || ''
  showDestinationDropdown.value = false
}

// Can search
const canSearch = computed(() => {
  return !!selectedProduct.value
})

// Search handler
const handleSearch = () => {
  if (!canSearch.value) return

  const params: Record<string, string> = {}
  if (selectedProduct.value?.uuid) {
    params.product = selectedProduct.value.uuid
  }
  if (quantity.value) {
    params.quantity = String(quantity.value)
    params.unit = unit.value
  }
  if (selectedDestination.value?.uuid) {
    params.destination = selectedDestination.value.uuid
  }

  router.push({
    path: localePath('/catalog/offers'),
    query: params
  })

  emit('search', {
    productUuid: selectedProduct.value?.uuid,
    quantity: quantity.value,
    unit: unit.value,
    destinationUuid: selectedDestination.value?.uuid
  })
}

// Load products on mount
onMounted(async () => {
  try {
    const { query } = useGraphQL()
    const { GetProductsDocument } = await import('~/composables/graphql/public/exchange-generated')
    const result = await query(GetProductsDocument, {}, 'exchange', 'public')
    allProducts.value = result.getProducts || []
  } catch (error) {
    console.error('Failed to load products:', error)
  }
})

// Close dropdowns on click outside
onMounted(() => {
  const handler = (e: MouseEvent) => {
    const target = e.target as HTMLElement
    if (!target.closest('.dropdown')) {
      showProductDropdown.value = false
      showDestinationDropdown.value = false
    }
  }
  document.addEventListener('click', handler)
  onUnmounted(() => document.removeEventListener('click', handler))
})
</script>

