<template>
  <CatalogPage
    :items="displayItems"
    :map-items="mapPoints"
    :loading="isLoading"
    with-map
    map-id="orders-map"
    point-color="#6366f1"
    :selected-id="selectedOrderId"
    :hovered-id="hoveredOrderId"
    :total-count="filteredItems.length"
    @select="onSelectOrder"
    @update:hovered-id="hoveredOrderId = $event"
  >
    <template #searchBar="{ displayedCount, totalCount }">
      <CatalogSearchBar
        v-model:search-query="searchQuery"
        :active-filters="activeFilterBadges"
        :displayed-count="displayedCount"
        :total-count="totalCount"
        @remove-filter="onRemoveFilter"
        @search="onSearch"
      >
        <template #filters>
          <div class="p-2 space-y-3">
            <div>
              <div class="text-xs font-semibold mb-1 text-base-content/70">{{ t('ordersList.filters.status') }}</div>
              <ul class="menu menu-compact">
                <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>
        </template>
      </CatalogSearchBar>
    </template>

    <template #card="{ item }">
      <Card padding="lg" class="cursor-pointer">
        <Stack gap="4">
          <Stack direction="row" justify="between" align="center">
            <Stack gap="1">
              <Text size="sm" tone="muted">{{ t('ordersList.card.order_label') }}</Text>
              <Heading :level="3">#{{ item.name }}</Heading>
            </Stack>
            <div class="badge badge-outline">
              {{ getOrderStartDate(item) }} → {{ getOrderEndDate(item) }}
            </div>
          </Stack>

          <div class="divider my-0"></div>

          <Grid :cols="1" :md="3" :gap="3">
            <Stack gap="1">
              <Text size="sm" tone="muted">{{ t('ordersList.card.route') }}</Text>
              <Text weight="semibold">{{ item.sourceLocationName }} → {{ item.destinationLocationName }}</Text>
            </Stack>

            <Stack gap="1">
              <Text size="sm" tone="muted">{{ t('ordersList.card.product') }}</Text>
              <Text>
                {{ item.orderLines?.[0]?.productName || t('ordersList.card.product_loading') }}
                <template v-if="item.orderLines?.length > 1">
                  <span class="badge badge-ghost ml-2">+{{ item.orderLines.length - 1 }}</span>
                </template>
              </Text>
              <Text tone="muted" size="sm">
                {{ item.orderLines?.[0]?.quantity || 0 }} {{ item.orderLines?.[0]?.unit || t('ordersList.card.unit_tons') }}
              </Text>
            </Stack>

            <Stack gap="1">
              <Text size="sm" tone="muted">{{ t('ordersList.card.status') }}</Text>
              <Badge :variant="getStatusVariant(item.status)">
                {{ getStatusText(item.status) }}
              </Badge>
              <Text tone="muted" size="sm">{{ t('ordersList.card.stages_completed', { done: getCompletedStages(item), total: item.stages?.length || 0 }) }}</Text>
            </Stack>
          </Grid>
        </Stack>
      </Card>
    </template>

    <template #empty>
      <EmptyState
        icon="📦"
        :title="t('orders.no_orders')"
        :description="t('orders.no_orders_desc')"
        :action-label="t('orders.create_new')"
        :action-to="localePath('/clientarea')"
        action-icon="lucide:plus"
      />
    </template>
  </CatalogPage>
</template>

<script setup lang="ts">
import type { MapBounds } from '~/components/catalog/CatalogMap.vue'

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

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

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

const selectedOrderId = ref<string>()
const hoveredOrderId = ref<string>()

// Search bar
const searchQuery = ref('')

// Search with map checkbox
const searchWithMap = ref(false)
const currentBounds = ref<MapBounds | null>(null)

// List items - one per order
const listItems = computed(() => {
  return filteredItems.value.map(order => ({
    ...order,
    uuid: order.uuid,
    name: order.name || `#${order.uuid.slice(0, 8)}`,
    latitude: order.sourceLatitude,
    longitude: order.sourceLongitude,
    country: order.sourceLocationName
  }))
})

// Map points - two per order (source + destination)
const mapPoints = computed(() => {
  const result: any[] = []
  filteredItems.value.forEach(order => {
    // Source point
    if (order.sourceLatitude && order.sourceLongitude) {
      result.push({
        uuid: `${order.uuid}-source`,
        name: `📦 ${order.sourceLocationName}`,
        latitude: order.sourceLatitude,
        longitude: order.sourceLongitude
      })
    }
    // Destination point - get from last stage
    const lastStage = order.stages?.[order.stages.length - 1]
    if (lastStage?.destinationLatitude && lastStage?.destinationLongitude) {
      result.push({
        uuid: `${order.uuid}-dest`,
        name: `🏁 ${order.destinationLocationName}`,
        latitude: lastStage.destinationLatitude,
        longitude: lastStage.destinationLongitude
      })
    }
  })
  return result
})

// Filtered items when searchWithMap is enabled
const displayItems = computed(() => {
  if (!searchWithMap.value || !currentBounds.value) return listItems.value
  return listItems.value.filter(item => {
    if (item.latitude == null || item.longitude == null) return false
    const { west, east, north, south } = currentBounds.value!
    const lng = Number(item.longitude)
    const lat = Number(item.latitude)
    return lng >= west && lng <= east && lat >= south && lat <= north
  })
})

// Active filter badges
const activeFilterBadges = computed(() => {
  const badges: { id: string; label: string }[] = []
  if (selectedFilter.value && selectedFilter.value !== 'all') {
    const filter = filters.value.find(f => f.id === selectedFilter.value)
    if (filter) badges.push({ id: `status:${filter.id}`, label: filter.label })
  }
  return badges
})

// Remove filter badge
const onRemoveFilter = (id: string) => {
  if (id.startsWith('status:')) {
    selectedFilter.value = 'all'
  }
}

// Search handler
const onSearch = () => {
  // TODO: Implement search
}

const onSelectOrder = (item: any) => {
  selectedOrderId.value = item.uuid
  navigateTo(localePath(`/clientarea/orders/${item.uuid}`))
}

await init()

const getOrderStartDate = (order: any) => {
  if (!order.createdAt) return t('ordersDetail.labels.dates_undefined')
  return formatDate(order.createdAt)
}

const getOrderEndDate = (order: any) => {
  let latestDate: Date | null = null
  order.stages?.forEach((stage: any) => {
    stage.trips?.forEach((trip: any) => {
      const endDate = trip.actualUnloadingDate || trip.plannedUnloadingDate
      if (endDate) {
        const date = new Date(endDate)
        if (!latestDate || date > latestDate) {
          latestDate = date
        }
      }
    })
  })
  if (latestDate) return formatDate((latestDate as Date).toISOString())
  if (order.createdAt) {
    const fallbackDate = new Date(order.createdAt)
    fallbackDate.setMonth(fallbackDate.getMonth() + 1)
    return formatDate(fallbackDate.toISOString())
  }
  return t('ordersDetail.labels.dates_undefined')
}

const getCompletedStages = (order: any) => {
  if (!order.stages?.length) return 0
  return order.stages.filter((stage: any) => stage.status === 'completed').length
}

const formatDate = (date: string) => {
  if (!date) return t('ordersDetail.labels.dates_undefined')
  try {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    if (isNaN(dateObj.getTime())) return t('ordersDetail.labels.dates_undefined')
    return new Intl.DateTimeFormat('ru-RU', {
      day: 'numeric',
      month: 'long',
      year: 'numeric'
    }).format(dateObj)
  } catch {
    return t('ordersDetail.labels.dates_undefined')
  }
}
</script>
