<template>
  <div class="fixed inset-0 flex flex-col">
    <!-- Fullscreen Map -->
    <div class="absolute inset-0">
      <ClientOnly>
        <CatalogMap
          ref="mapRef"
          map-id="step-quantity-map"
          :items="mapPoints"
          :use-server-clustering="false"
          point-color="#22c55e"
          entity-type="hub"
          :related-points="relatedPoints"
          :info-loading="false"
          @bounds-change="() => {}"
        />
      </ClientOnly>
    </div>

    <!-- Bottom sheet card -->
    <div class="fixed inset-x-0 bottom-0 z-10 flex flex-col items-center pointer-events-none">
      <article
        class="w-full max-w-[980px] rounded-t-3xl bg-white shadow-[0_-8px_40px_rgba(0,0,0,0.12)] pointer-events-auto flex flex-col"
        style="max-height: 60vh"
      >
        <div class="shrink-0 p-5 md:px-7 md:pt-7">
          <div class="flex justify-center mb-4">
            <div class="w-10 h-1 bg-base-300 rounded-full" />
          </div>

          <p class="text-xs font-bold uppercase tracking-wider text-base-content/50">{{ $t('catalog.step', { n: 3 }) }}</p>
          <h2 class="text-2xl font-black tracking-tight text-base-content mb-4">{{ $t('catalog.steps.setQuantity') }}</h2>

          <!-- Selected product + hub chips -->
          <div class="flex flex-wrap items-center gap-2 mb-6">
            <span v-if="productName" class="badge badge-warning gap-1">
              <Icon name="lucide:package" size="12" />
              {{ productName }}
            </span>
            <Icon name="lucide:arrow-right" size="14" class="text-base-content/30" />
            <span v-if="hubName" class="badge badge-success gap-1">
              <Icon name="lucide:warehouse" size="12" />
              {{ hubName }}
            </span>
          </div>

          <!-- Quantity input -->
          <div class="form-control w-full max-w-xs">
            <label class="label">
              <span class="label-text font-bold">{{ $t('catalog.filters.quantity') }}</span>
            </label>
            <label class="input input-bordered rounded-xl flex items-center gap-2">
              <input
                v-model="qty"
                type="number"
                min="0"
                step="0.1"
                placeholder="100"
                class="grow bg-transparent [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
              />
              <span class="text-base-content/50 text-sm">{{ $t('units.t') }}</span>
            </label>
          </div>

          <!-- Search button -->
          <button
            class="btn btn-primary w-full mt-6 rounded-full text-base font-bold"
            :disabled="!canSearch"
            @click="goSearch"
          >
            <Icon name="lucide:search" size="18" />
            {{ $t('catalog.quote.findOffers') }}
          </button>
        </div>
      </article>
    </div>
  </div>
</template>

<script setup lang="ts">
import { GetNodeDocument } from '~/composables/graphql/public/geo-generated'

definePageMeta({ layout: 'topnav' })

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

const mapRef = ref(null)
const qty = ref('100')

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

const canSearch = computed(() => !!(productUuid.value && hubUuid.value))

// Load hub coordinates for map
const hubPoint = ref<{ uuid: string; name: string; latitude: number; longitude: number } | null>(null)

const loadHubPoint = async () => {
  if (!hubUuid.value) return
  const data = await execute(GetNodeDocument, { uuid: hubUuid.value }, 'public', 'geo')
  const node = data?.node
  if (node?.latitude != null && node?.longitude != null) {
    hubPoint.value = {
      uuid: node.uuid,
      name: node.name || hubName.value || '',
      latitude: Number(node.latitude),
      longitude: Number(node.longitude),
    }
  }
}

const mapPoints = computed(() => hubPoint.value ? [hubPoint.value] : [])

const relatedPoints = computed(() => {
  if (!hubPoint.value) return []
  return [{
    uuid: hubPoint.value.uuid,
    name: hubPoint.value.name,
    latitude: hubPoint.value.latitude,
    longitude: hubPoint.value.longitude,
    type: 'hub' as const,
  }]
})

const goSearch = () => {
  const query: Record<string, string> = {
    ...route.query as Record<string, string>,
  }
  if (qty.value) query.qty = qty.value

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

onMounted(() => {
  loadHubPoint()
})

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