<template>
  <div class="fixed inset-0">
    <ClientOnly>
      <CatalogMap
        map-id="step-results-map"
        :items="mapItems"
        :use-server-clustering="false"
        point-color="#f97316"
        entity-type="offer"
        :related-points="relatedPoints"
        :info-loading="offersLoading"
        :fit-padding-left="460"
        @select-item="onMapSelect"
      />
    </ClientOnly>

    <MapSidePanel
      :title="t('catalog.headers.offers')"
      :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.steps.results') }}</p>

        <div class="flex flex-wrap items-center gap-2">
          <span v-if="productName" class="inline-flex items-center gap-1.5 rounded-full border border-[#ded3c2] bg-white px-3 py-1 text-xs font-medium text-[#6f6353]">
            <Icon name="lucide:package" size="12" />
            {{ productName }}
          </span>
          <span v-if="hubName" class="inline-flex items-center gap-1.5 rounded-full border border-[#ded3c2] bg-white px-3 py-1 text-xs font-medium text-[#6f6353]">
            <Icon name="lucide:warehouse" size="12" />
            {{ hubName }}
          </span>
          <span v-if="qty" class="inline-flex items-center gap-1.5 rounded-full border border-[#ded3c2] bg-white px-3 py-1 text-xs font-medium text-[#6f6353]">
            {{ qty }} {{ $t('units.t') }}
          </span>
          <span v-if="!offersLoading" class="badge badge-neutral ml-auto">{{ offers.length }}</span>
        </div>
      </div>

      <div class="mt-4 flex flex-col gap-3">
        <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="rounded-2xl border border-[#e4d9ca] bg-white px-4 py-8 text-center text-[#7c6d5a]">
          <Icon name="lucide:search-x" size="30" class="mx-auto mb-2" />
          <p>{{ $t('catalog.empty.noOffers') }}</p>
        </div>

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

      <template #footer>
        <div class="flex items-center gap-2">
          <button class="btn btn-sm rounded-full border-[#d7c9b7] bg-white text-[#2f2418] hover:bg-[#f7f1e8]" @click="goBack">
            <Icon name="lucide:refresh-cw" size="14" />
            {{ $t('catalog.steps.newSearch') }}
          </button>
        </div>
      </template>
    </MapSidePanel>
  </div>
</template>

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

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

definePageMeta({ layout: 'topnav' })

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

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)

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

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

const mapItems = computed(() =>
  offers.value
    .filter(o => o.uuid && o.latitude != null && o.longitude != null)
    .map(o => ({
      uuid: o.uuid,
      name: o.productName || '',
      latitude: Number(o.latitude),
      longitude: Number(o.longitude),
    }))
)

const relatedPoints = computed(() => {
  const points: Array<{ uuid: string; name: string; latitude: number; longitude: number; type: 'hub' | '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.uuid && o.latitude != null && o.longitude != null)
    .forEach(o => {
      points.push({
        uuid: o.uuid,
        name: o.productName || '',
        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 selectedProductUuid = offer.productUuid
  if (offer.uuid && selectedProductUuid) {
    router.push(localePath(`/catalog/offers/${selectedProductUuid}?offer=${offer.uuid}`))
  }
}

const getOfferStages = (offer: NearestOffer) => {
  const firstRoute = offer.routes?.[0]
  if (!firstRoute?.stages) return []

  return firstRoute.stages
    .filter((stage): stage is NonNullable<typeof stage> => stage !== null)
    .map(stage => ({
      transportType: stage.transportType,
      distanceKm: stage.distanceKm,
      travelTimeSeconds: stage.travelTimeSeconds,
      fromName: stage.fromName,
    }))
}

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

const searchOffers = async () => {
  if (!productUuid.value || !hubUuid.value) return

  offersLoading.value = true
  try {
    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),
    }

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

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

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

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