<template>
  <NuxtLayout name="map">
    <template #sidebar>
      <CatalogMapSidebar
        :title="t('dashboard.orders')"
        :back-link="localePath('/clientarea/orders')"
        :back-label="t('catalogMap.actions.list_view')"
        :items-count="filteredItems.length"
        :filters="filters"
        :selected-filter="selectedFilter"
        :loading="isLoading"
        :empty-text="t('orders.no_orders')"
        @update:selected-filter="selectedFilter = $event"
      >
        <template #cards>
          <Card
            v-for="(order, index) in filteredItems"
            :key="order.uuid ?? index"
            padding="small"
            interactive
            :class="{ 'ring-2 ring-primary': selectedOrderId === order.uuid }"
            @click="selectOrder(order)"
          >
            <Stack gap="2">
              <Stack direction="row" justify="between" align="center">
                <Text weight="semibold">#{{ order.name }}</Text>
                <Badge :variant="getStatusVariant(order.status || '')" size="sm">
                  {{ getStatusText(order.status || '') }}
                </Badge>
              </Stack>
              <Text tone="muted" size="sm" class="truncate">
                {{ order.sourceLocationName }} → {{ order.destinationLocationName }}
              </Text>
            </Stack>
          </Card>
        </template>
      </CatalogMapSidebar>
    </template>

    <ClientOnly>
      <OrdersRoutesMap
        ref="mapRef"
        :routes="routesForMap"
        :selected-order-id="selectedOrderId"
        @select-order="onMapSelectOrder"
      />
    </ClientOnly>
  </NuxtLayout>
</template>

<script setup lang="ts">
definePageMeta({
  layout: false,
  middleware: ['auth-oidc']
})

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

const {
  filteredItems,
  isLoading,
  filters,
  selectedFilter,
  routesForMap,
  init,
  getStatusVariant,
  getStatusText
} = useTeamOrders()

await init()

const mapRef = ref<{ flyTo: (orderId: string) => void } | null>(null)
const selectedOrderId = ref<string | null>(null)

const selectOrder = (order: { uuid?: string | null }) => {
  if (order.uuid) {
    selectedOrderId.value = order.uuid
    mapRef.value?.flyTo(order.uuid)
  }
}

const onMapSelectOrder = (uuid: string) => {
  selectedOrderId.value = uuid
}
</script>
