<template>
  <div class="fixed inset-0 flex flex-col">
    <!-- Fullscreen Map -->
    <div class="absolute inset-0">
      <ClientOnly>
        <CatalogMap
          ref="mapRef"
          map-id="step-results-map"
          :items="[]"
          :use-server-clustering="false"
          point-color="#f97316"
          entity-type="offer"
          :related-points="relatedPoints"
          :info-loading="offersLoading"
          @select-item="onMapSelect"
          @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"
      >
        <!-- Header -->
        <div class="shrink-0 p-5 pb-0 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>

          <div class="flex items-center justify-between mb-1">
            <div>
              <p class="text-xs font-bold uppercase tracking-wider text-base-content/50">{{ $t('catalog.steps.results') }}</p>
              <h2 class="text-2xl font-black tracking-tight text-base-content">{{ $t('catalog.headers.offers') }}</h2>
            </div>
            <span v-if="!offersLoading" class="badge badge-neutral">{{ offers.length }}</span>
          </div>

          <!-- Selected filters summary -->
          <div class="flex flex-wrap items-center gap-2 mt-2">
            <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>
            <span v-if="qty" class="badge badge-info gap-1">
              {{ qty }} {{ $t('units.t') }}
            </span>
          </div>
        </div>

        <!-- Offers list -->
        <div class="min-h-0 flex-1 overflow-y-auto p-5 md:px-7">
          <div v-if="offersLoading" class="flex items-center justify-center py-8">
            <span class="loading loading-spinner loading-md" />
          </div>

          <div v-else-if="offers.length === 0" class="text-center py-8 text-base-content/50">
            <Icon name="lucide:search-x" size="32" class="mb-2" />
            <p>{{ $t('catalog.empty.noOffers') }}</p>
            <button class="btn btn-ghost btn-sm mt-3" @click="goBack">
              <Icon name="lucide:arrow-left" size="16" />
              {{ $t('common.back') }}
            </button>
          </div>

          <div v-else class="flex flex-col gap-3">
            <div
              v-for="offer in offers"
              :key="offer.uuid"
              class="cursor-pointer"
              @click="onSelectOffer(offer)"
            >
              <OfferResultCard
                :supplier-name="offer.supplier_name"
                :location-name="offer.country || ''"
                :product-name="offer.product_name"
                :price-per-unit="offer.price_per_unit ? Number(offer.price_per_unit) : null"
                :quantity="offer.quantity"
                :currency="offer.currency"
                :unit="offer.unit"
                :stages="getOfferStages(offer)"
                :total-time-seconds="offer.routes?.[0]?.total_time_seconds ?? null"
              />
            </div>
          </div>
        </div>

        <!-- New search button -->
        <div class="shrink-0 p-5 pt-0 md:px-7">
          <button class="btn btn-outline btn-sm w-full rounded-full" @click="goBack">
            <Icon name="lucide:refresh-cw" size="14" />
            {{ $t('catalog.steps.newSearch') }}
          </button>
        </div>
      </article>
    </div>
  </div>
</template>

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

type NearestOffer = NonNullable<NearestOffersQueryResult['nearest_offers'][number]>

definePageMeta({ layout: 'topnav' })

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

const mapRef = ref(null)

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 qty = computed(() => route.query.qty as string | undefined)

// Offers data
const offers = ref<NearestOffer[]>([])
const offersLoading = ref(false)

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

// Related points for map (hub + offer locations)
const relatedPoints = computed(() => {
  const points: Array<{ uuid: string; name: string; latitude: number; longitude: number; type: 'hub' | 'supplier' | 'offer' }> = []

  if (hubPoint.value) {
    points.push({
      uuid: hubPoint.value.uuid,
      name: hubPoint.value.name,
      latitude: hubPoint.value.latitude,
      longitude: hubPoint.value.longitude,
      type: 'hub',
    })
  }

  offers.value
    .filter(o => o.latitude != null && o.longitude != null)
    .forEach(o => {
      points.push({
        uuid: o.uuid,
        name: o.product_name || '',
        latitude: Number(o.latitude),
        longitude: Number(o.longitude),
        type: 'offer',
      })
    })

  return points
})

const onMapSelect = (uuid: string) => {
  const offer = offers.value.find(o => o.uuid === uuid)
  if (offer) onSelectOffer(offer)
}

const onSelectOffer = (offer: NearestOffer) => {
  const productUuid = offer.product_uuid || offer.productUuid
  if (offer.uuid && productUuid) {
    router.push(localePath(`/catalog/offers/${productUuid}?offer=${offer.uuid}`))
  }
}

const getOfferStages = (offer: NearestOffer) => {
  const r = offer.routes?.[0]
  if (!r?.stages) return []
  return r.stages
    .filter((s): s is NonNullable<typeof s> => s !== null)
    .map(s => ({
      transportType: s.transport_type,
      distanceKm: s.distance_km,
      travelTimeSeconds: s.travel_time_seconds,
      fromName: s.from_name,
    }))
}

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

// Search for offers
const searchOffers = async () => {
  if (!productUuid.value || !hubUuid.value) return
  offersLoading.value = true
  try {
    // Load hub coordinates
    const hubData = await execute(GetNodeDocument, { uuid: hubUuid.value }, 'public', 'geo')
    const hub = hubData?.node
    if (!hub?.latitude || !hub?.longitude) {
      offers.value = []
      return
    }

    hubPoint.value = {
      uuid: hub.uuid,
      name: hub.name || hubName.value || '',
      latitude: Number(hub.latitude),
      longitude: Number(hub.longitude),
    }

    // Search nearest offers
    const data = await execute(
      NearestOffersDocument,
      {
        lat: hub.latitude,
        lon: hub.longitude,
        productUuid: productUuid.value,
        hubUuid: hubUuid.value,
        limit: 20,
      },
      'public',
      'geo'
    )

    offers.value = (data?.nearest_offers || []).filter((o): o is NearestOffer => o !== null)
  } finally {
    offersLoading.value = false
  }
}

onMounted(() => {
  searchOffers()
})

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