<template>
  <div class="fixed inset-0">
    <ClientOnly>
      <CatalogMap
        map-id="step-hub-map"
        :items="hubMapItems"
        :use-server-clustering="false"
        point-color="#22c55e"
        entity-type="hub"
        :fit-padding-left="460"
        @select-item="onMapSelect"
      />
    </ClientOnly>

    <MapSidePanel
      :title="t('catalog.steps.selectDestination')"
      :initial-collapsed="false"
      width-class="w-[min(calc(100vw-1rem),440px)] md:w-[420px] xl:w-[460px]"
    >
      <div class="space-y-3">
        <p class="text-xs font-bold uppercase tracking-wider text-[#8a7761]">{{ $t('catalog.step', { n: 2 }) }}</p>

        <div v-if="productName" class="inline-flex items-center gap-2 rounded-full border border-[#ded3c2] bg-white px-3 py-1.5 text-xs font-medium text-[#6f6353]">
          <Icon name="lucide:package" size="14" />
          <span class="truncate">{{ productName }}</span>
        </div>

        <label class="input w-full rounded-full bg-white border-[#dccfbf] flex items-center gap-2">
          <Icon name="lucide:search" size="16" class="text-[#8a7761]" />
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="$t('catalog.search.searchHubs')"
            class="grow bg-transparent"
          >
        </label>
      </div>

      <div class="mt-4 flex flex-col gap-2">
        <div v-if="isLoading" class="flex items-center justify-center py-8">
          <span class="loading loading-spinner loading-md" />
        </div>

        <div v-else-if="filteredHubs.length === 0" class="rounded-2xl border border-[#e4d9ca] bg-white px-4 py-8 text-center text-[#7c6d5a]">
          <Icon name="lucide:warehouse" size="30" class="mx-auto mb-2" />
          <p>{{ $t('catalog.empty.noHubs') }}</p>
        </div>

        <button
          v-for="hub in filteredHubs"
          v-else
          :key="hub.uuid"
          class="flex items-center gap-4 rounded-2xl border border-[#e4d9ca] bg-white p-4 text-left transition-colors hover:bg-[#f8f3ec]"
          @click="selectHub(hub)"
        >
          <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-green-400 to-green-600 shadow-lg">
            <Icon name="lucide:warehouse" size="20" class="text-white" />
          </div>
          <div class="min-w-0 flex-1">
            <span class="block truncate text-base font-bold text-[#2f2418]">{{ hub.name || hub.uuid }}</span>
            <span v-if="hub.country" class="text-sm text-[#7a6d5d]">{{ hub.country }}</span>
          </div>
          <Icon name="lucide:chevron-right" size="18" class="text-[#8a7761]" />
        </button>
      </div>

      <template #footer>
        <button
          class="btn btn-sm rounded-full border-[#d7c9b7] bg-white text-[#2f2418] hover:bg-[#f7f1e8]"
          @click="goBack"
        >
          <Icon name="lucide:arrow-left" size="14" />
          {{ $t('common.back') }}
        </button>
      </template>
    </MapSidePanel>
  </div>
</template>

<script setup lang="ts">
definePageMeta({ layout: 'topnav' })

const { t } = useI18n()
const router = useRouter()
const localePath = useLocalePath()
const route = useRoute()

const searchQuery = ref('')

const productUuid = computed(() => route.query.product as string | undefined)
const productName = computed(() => route.query.productName as string | undefined)

const { items: hubs, isLoading, init: initHubs, setProductFilter } = useCatalogHubs()

const hubMapItems = computed(() =>
  hubs.value
    .filter(h => h.latitude != null && h.longitude != null && h.uuid)
    .map(h => ({
      uuid: h.uuid!,
      name: h.name || '',
      latitude: Number(h.latitude),
      longitude: Number(h.longitude),
      country: h.country || undefined,
    }))
)

const onMapSelect = (uuid: string) => {
  const hub = hubs.value.find(h => h.uuid === uuid)
  if (hub) selectHub(hub)
}

const filteredHubs = computed(() => {
  if (!searchQuery.value.trim()) return hubs.value
  const q = searchQuery.value.toLowerCase().trim()
  return hubs.value.filter(h =>
    (h.name || '').toLowerCase().includes(q) ||
    (h.country || '').toLowerCase().includes(q)
  )
})

const selectHub = (hub: { uuid?: string | null; name?: string | null }) => {
  if (!hub.uuid) return

  const query: Record<string, string> = {
    ...route.query as Record<string, string>,
    hub: hub.uuid,
  }

  if (hub.name) query.hubName = hub.name

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

const goBack = () => {
  router.push({
    path: localePath('/catalog/product'),
    query: route.query,
  })
}

onMounted(() => {
  if (productUuid.value) {
    setProductFilter(productUuid.value)
  }
  initHubs()
})

useHead(() => ({
  title: t('catalog.steps.selectDestination')
}))
</script>
