<template>
  <div>
    <CatalogPage
      :items="mapPoints"
      :loading="isLoading"
      :use-server-clustering="false"
      map-id="orders-map"
      point-color="#6366f1"
      :hovered-id="hoveredOrderId"
      :show-panel="!selectedOrderId"
      panel-width="w-96"
      :hide-view-toggle="true"
      @select="onMapSelect"
      @update:hovered-id="hoveredOrderId = $event"
    >
    <template #panel>
      <!-- Panel header -->
      <div class="p-4 border-b border-white/10 flex-shrink-0">
        <div class="flex items-center justify-between mb-3">
          <div class="flex items-center gap-2">
            <div class="w-8 h-8 rounded-lg bg-indigo-500/20 flex items-center justify-center">
              <Icon name="lucide:package" size="16" class="text-indigo-400" />
            </div>
            <div>
              <span class="font-semibold text-sm">{{ t('cabinetNav.orders') }}</span>
              <div class="text-xs text-white/50">{{ filteredItems.length }} {{ t('orders.total', 'total') }}</div>
            </div>
          </div>
        </div>

        <!-- Search -->
        <div class="relative mb-3">
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="t('common.search')"
            class="input input-sm w-full bg-white/10 border-white/20 text-white placeholder:text-white/50"
          />
          <Icon name="lucide:search" size="16" class="absolute right-3 top-1/2 -translate-y-1/2 text-white/50" />
        </div>

        <!-- Filter dropdown -->
        <div class="dropdown dropdown-end w-full">
          <label tabindex="0" class="btn btn-sm w-full bg-white/10 border-white/20 text-white hover:bg-white/20 justify-between">
            <span>{{ selectedFilterLabel }}</span>
            <Icon name="lucide:chevron-down" size="14" />
          </label>
          <ul tabindex="0" class="dropdown-content menu menu-sm z-50 p-2 shadow bg-base-200 rounded-box w-full mt-2">
            <li v-for="filter in filters" :key="filter.id">
              <a
                :class="{ 'active': selectedFilter === filter.id }"
                @click="selectedFilter = filter.id"
              >{{ filter.label }}</a>
            </li>
          </ul>
        </div>
      </div>

      <!-- Orders list -->
      <div class="flex-1 overflow-y-auto p-3 space-y-2">
        <template v-if="displayItems.length > 0">
          <div
            v-for="item in displayItems"
            :key="item.uuid"
            class="bg-white/10 rounded-lg p-3 hover:bg-white/20 transition-colors cursor-pointer"
            :class="{ 'ring-2 ring-indigo-500': selectedOrderId === item.uuid }"
            @click="selectedOrderId = item.uuid"
            @mouseenter="hoveredOrderId = item.uuid"
            @mouseleave="hoveredOrderId = undefined"
          >
            <div class="flex items-center justify-between mb-2">
              <span class="font-semibold text-sm">#{{ item.name }}</span>
              <span class="badge badge-sm" :class="getStatusBadgeClass(item.status)">
                {{ getStatusText(item.status) }}
              </span>
            </div>
            <div class="text-xs text-white/70 space-y-1">
              <div class="flex items-center gap-2">
                <Icon name="lucide:map-pin" size="12" class="text-white/40" />
                <span class="truncate">{{ item.sourceLocationName }}</span>
              </div>
              <div class="flex items-center gap-2">
                <Icon name="lucide:navigation" size="12" class="text-white/40" />
                <span class="truncate">{{ item.destinationLocationName }}</span>
              </div>
            </div>
            <div class="text-xs text-white/50 mt-2">
              {{ getOrderDate(item) }}
            </div>
          </div>
        </template>
        <template v-else>
          <div class="text-center py-8">
            <div class="text-3xl mb-2">📦</div>
            <div class="font-semibold text-sm mb-1">{{ t('orders.no_orders') }}</div>
            <div class="text-xs text-white/60">{{ t('orders.no_orders_desc') }}</div>
          </div>
        </template>
      </div>

      <!-- Footer -->
      <div class="p-3 border-t border-white/10 flex-shrink-0">
        <span class="text-xs text-white/50">{{ displayItems.length }} {{ t('catalog.of') }} {{ filteredItems.length }}</span>
      </div>
    </template>
    </CatalogPage>

    <!-- Order Detail Bottom Sheet -->
    <OrderDetailBottomSheet
      :is-open="!!selectedOrderId"
      :order-uuid="selectedOrderId"
      @close="selectedOrderId = null"
    />
  </div>
</template>

<script setup lang="ts">
import type { GetTeamOrdersQueryResult } from '~/composables/graphql/team/orders-generated'

type TeamOrder = NonNullable<NonNullable<GetTeamOrdersQueryResult['getTeamOrders']>[number]>

definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

const { t } = useI18n()

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

const hoveredOrderId = ref<string>()
const searchQuery = ref('')
const selectedOrderId = ref<string | null>(null)

// Selected filter label
const selectedFilterLabel = computed(() => {
  const filter = filters.value.find(f => f.id === selectedFilter.value)
  return filter?.label || t('ordersList.filters.status')
})

// Map points - source locations
const mapPoints = computed(() => {
  return filteredItems.value
    .filter(order => order.uuid && order.sourceLatitude && order.sourceLongitude)
    .map(order => ({
      uuid: order.uuid!,
      name: order.name || `#${order.uuid!.slice(0, 8)}`,
      latitude: order.sourceLatitude!,
      longitude: order.sourceLongitude!
    }))
})

// Display items with search filter
const displayItems = computed(() => {
  let items = filteredItems.value.filter(order => order.uuid)

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    items = items.filter(item =>
      item.name?.toLowerCase().includes(query) ||
      item.sourceLocationName?.toLowerCase().includes(query) ||
      item.destinationLocationName?.toLowerCase().includes(query)
    )
  }

  return items
})

const onMapSelect = (item: { uuid?: string | null }) => {
  if (item.uuid) {
    selectedOrderId.value = item.uuid
  }
}

await init()

const getOrderDate = (order: TeamOrder) => {
  if (!order.createdAt) return ''
  try {
    return new Intl.DateTimeFormat('ru-RU', {
      day: 'numeric',
      month: 'short'
    }).format(new Date(order.createdAt))
  } catch {
    return ''
  }
}

const getStatusBadgeClass = (status?: string) => {
  const variant = getStatusVariant(status)
  switch (variant) {
    case 'success': return 'badge-success'
    case 'warning': return 'badge-warning'
    case 'error': return 'badge-error'
    default: return 'badge-ghost'
  }
}
</script>
