<template>
  <Section variant="plain" paddingY="md">
    <Stack gap="6">
      <Alert v-if="hasError" variant="error">
        <Stack gap="2">
          <Heading :level="4" weight="semibold">{{ $t('common.error') }}</Heading>
          <Text tone="muted">{{ error }}</Text>
          <Button @click="load">{{ t('ordersList.errors.retry') }}</Button>
        </Stack>
      </Alert>

      <Stack v-else-if="isLoading" align="center" justify="center" gap="3">
        <Spinner />
        <Text tone="muted">{{ t('ordersList.states.loading') }}</Text>
      </Stack>

      <template v-else>
        <template v-if="items.length">
          <NuxtLink :to="localePath('/clientarea/orders/map')" class="block h-48 rounded-lg overflow-hidden cursor-pointer">
            <ClientOnly>
              <OrdersRoutesPreview :routes="routesForMap" :height="192" />
            </ClientOnly>
          </NuxtLink>

          <CatalogFilters :filters="filters" v-model="selectedFilter" />

          <Stack gap="4">
            <Card v-for="order in filteredItems" :key="order.uuid" padding="lg" class="cursor-pointer" @click="openOrder(order)">
              <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">#{{ order.name }}</Heading>
                  </Stack>
                  <div class="badge badge-outline">
                    {{ getOrderStartDate(order) }} → {{ getOrderEndDate(order) }}
                  </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">{{ order.sourceLocationName }} → {{ order.destinationLocationName }}</Text>
                  </Stack>

                  <Stack gap="1">
                    <Text size="sm" tone="muted">{{ t('ordersList.card.product') }}</Text>
                    <Text>
                      {{ order.orderLines?.[0]?.productName || t('ordersList.card.product_loading') }}
                      <template v-if="order.orderLines?.length > 1">
                        <span class="badge badge-ghost ml-2">+{{ order.orderLines.length - 1 }}</span>
                      </template>
                    </Text>
                    <Text tone="muted" size="sm">
                      {{ order.orderLines?.[0]?.quantity || 0 }} {{ order.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(order.status)">
                      {{ getStatusText(order.status) }}
                    </Badge>
                    <Text tone="muted" size="sm">{{ t('ordersList.card.stages_completed', { done: getCompletedStages(order), total: order.stages?.length || 0 }) }}</Text>
                  </Stack>
                </Grid>
              </Stack>
            </Card>
          </Stack>
        </template>

        <EmptyState
          v-else
          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>
    </Stack>
  </Section>
</template>

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

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

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

const hasError = ref(false)
const error = ref('')

try {
  await init()
} catch (err: any) {
  hasError.value = true
  error.value = err.message || t('ordersDetail.errors.load_failed')
}

const openOrder = (order: any) => {
  navigateTo(localePath(`/clientarea/orders/${order.uuid}`))
}

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>
