<template>
  <Stack gap="8">
    <Section variant="hero">
      <Heading :level="1" tone="inverse">Каталог Optovia</Heading>
    </Section>

    <!-- Loading state -->
    <Section v-if="isLoading" variant="plain" paddingY="md">
      <Card>
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">Загружаем данные каталога...</Text>
        </Stack>
      </Card>
    </Section>

    <template v-else>
      <!-- Превью карты - кликабельная -->
      <Section variant="plain" paddingY="md">
        <div
          class="relative h-48 rounded-lg overflow-hidden cursor-pointer group"
          @click="showMapOverlay = true"
        >
          <ClientOnly>
            <MapboxGlobe
              :locations="mapLocations"
              :height="192"
            />
          </ClientOnly>
          <div class="absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors">
            <div class="flex items-center gap-2 px-4 py-2 bg-white rounded-lg shadow-lg">
              <Icon name="lucide:maximize-2" size="20" />
              <span class="font-medium">Открыть карту</span>
            </div>
          </div>
        </div>
      </Section>

      <!-- Секции -->
      <CatalogHubsSection :hubs="locations" />
      <CatalogOffersSection :offers="offers" />
      <CatalogSuppliersSection :suppliers="suppliers" />
    </template>

    <!-- Fullscreen карта overlay -->
    <Teleport to="body">
      <Transition
        enter-active-class="transition-opacity duration-300"
        enter-from-class="opacity-0"
        enter-to-class="opacity-100"
        leave-active-class="transition-opacity duration-200"
        leave-from-class="opacity-100"
        leave-to-class="opacity-0"
      >
        <div v-if="showMapOverlay" class="fixed inset-0 z-50 bg-white">
          <!-- Кнопка закрыть -->
          <button
            @click="showMapOverlay = false"
            class="absolute top-4 right-4 z-20 p-2 bg-white rounded-full shadow-lg hover:bg-gray-100 transition-colors"
          >
            <Icon name="lucide:x" size="24" />
          </button>

          <!-- Панель табов слева -->
          <div class="absolute left-4 top-4 bottom-4 w-80 z-10">
            <CatalogMapPanel
              ref="mapPanelRef"
              :hubs="locations"
              :offers="offers"
              :suppliers="suppliers"
              @fly-to="handleFlyTo"
            />
          </div>

          <!-- Карта на весь экран -->
          <ClientOnly>
            <MapboxGlobe
              ref="fullscreenMapRef"
              :locations="mapLocations"
              :height="'100vh'"
              :selected-location-id="selectedLocationId"
              @location-click="handleLocationClick"
            />
          </ClientOnly>
        </div>
      </Transition>
    </Teleport>
  </Stack>
</template>

<script setup lang="ts">
import {
  GetLogisticsNodesDocument,
  GetSuppliersDocument,
  GetOffersDocument
} from '~/composables/graphql/public/exchange-generated'

const { execute } = useGraphQL()

const isLoading = ref(true)
const showMapOverlay = ref(false)
const suppliers = ref<any[]>([])
const offers = ref<any[]>([])
const locations = ref<any[]>([])
const selectedLocationId = ref<string | null>(null)
const fullscreenMapRef = ref<any>(null)

const calculateDistance = (lat: number, lng: number) => {
  const moscowLat = 55.76
  const moscowLng = 37.64
  const distance = Math.sqrt(Math.pow(lat - moscowLat, 2) + Math.pow(lng - moscowLng, 2)) * 111
  return `${Math.round(distance)} км`
}

// Собираем все локации для карты
const mapLocations = computed(() => {
  const locs: Array<{
    uuid: string | null | undefined
    name: string | null | undefined
    latitude: number | null | undefined
    longitude: number | null | undefined
    country: string | null | undefined
  }> = []

  // Хабы
  locations.value.forEach(hub => {
    if (hub.latitude && hub.longitude) {
      locs.push({
        uuid: hub.uuid,
        name: hub.name,
        latitude: hub.latitude,
        longitude: hub.longitude,
        country: hub.country
      })
    }
  })

  // Офферы (с маппингом координат)
  offers.value.forEach(offer => {
    const lat = offer.latitude || offer.locationLatitude
    const lng = offer.longitude || offer.locationLongitude
    if (lat && lng) {
      locs.push({
        uuid: offer.uuid,
        name: offer.title,
        latitude: lat,
        longitude: lng,
        country: offer.locationName
      })
    }
  })

  return locs
})

const handleFlyTo = (location: any) => {
  selectedLocationId.value = location.uuid
  if (fullscreenMapRef.value?.flyToLocation) {
    fullscreenMapRef.value.flyToLocation(location)
  }
}

const handleLocationClick = (location: any) => {
  selectedLocationId.value = location.uuid
}

onMounted(async () => {
  try {
    const [suppliersResult, offersResult, locationsResult] = await Promise.all([
      execute(GetSuppliersDocument, {}, 'public', 'exchange').catch(() => ({ getSuppliers: [] })),
      execute(GetOffersDocument, {}, 'public', 'exchange').catch(() => ({ getOffers: [] })),
      execute(GetLogisticsNodesDocument, {}, 'public', 'exchange').catch(() => ({ getLogisticsNodes: [] })),
    ])

    suppliers.value = suppliersResult.getSuppliers || []

    // Маппим координаты офферов
    offers.value = (offersResult.getOffers || []).map((offer: any) => ({
      ...offer,
      latitude: offer.locationLatitude,
      longitude: offer.locationLongitude
    }))

    locations.value = (locationsResult.getLogisticsNodes || []).map((location: any) => ({
      ...location,
      distance:
        location?.latitude && location?.longitude
          ? calculateDistance(location.latitude, location.longitude)
          : '—',
    }))
  } catch (error) {
    console.error('Error loading catalog data:', error)
  } finally {
    isLoading.value = false
  }
})

// Закрытие по Escape
onMounted(() => {
  const handleEscape = (e: KeyboardEvent) => {
    if (e.key === 'Escape' && showMapOverlay.value) {
      showMapOverlay.value = false
    }
  }
  document.addEventListener('keydown', handleEscape)
  onUnmounted(() => {
    document.removeEventListener('keydown', handleEscape)
  })
})
</script>
