<template>
  <Section variant="plain" paddingY="md">
    <Stack gap="6">
          <PageHeader
            :title="$t('dashboard.orders')"
            :actions="[{ label: t('ordersList.actions.new_calc'), icon: 'lucide:plus', to: localePath('/clientarea') }]"
          />

          <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="loadTeamOrders">{{ 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>
            <Stack v-if="orders.length" gap="4">
              <Card v-for="order in orders" :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>

            <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">
import { GetTeamOrdersDocument } from '~/composables/graphql/team/orders-generated'

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

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

const orders = ref<any[]>([])
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')

const loadTeamOrders = async () => {
  try {
    isLoading.value = true
    hasError.value = false
    const { data, error: ordersError } = await useServerQuery('orders-list', GetTeamOrdersDocument, {}, 'team', 'orders')
    if (ordersError.value) throw ordersError.value
    orders.value = data.value?.getTeamOrders || []
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || t('ordersDetail.errors.load_failed')
    orders.value = []
  } finally {
    isLoading.value = false
  }
}

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

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

const getOrderEndDate = (order) => {
  let latestDate = null
  order.stages?.forEach(stage => {
    stage.trips?.forEach(trip => {
      const endDate = trip.actualUnloadingDate || trip.plannedUnloadingDate
      if (endDate) {
        const date = new Date(endDate)
        if (!latestDate || date > latestDate) {
          latestDate = date
        }
      }
    })
  })
  if (latestDate) return formatDate(latestDate.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 getStatusText = (status) => {
  const texts = {
    pending: t('ordersDetail.status.pending'),
    processing: t('ordersDetail.status.processing'),
    in_transit: t('ordersDetail.status.in_transit'),
    delivered: t('ordersDetail.status.delivered'),
    cancelled: t('ordersDetail.status.cancelled')
  }
  return texts[status] || status || t('ordersDetail.status.unknown')
}

const getStatusVariant = (status) => {
  const variants = {
    pending: 'warning',
    processing: 'primary',
    in_transit: 'info',
    delivered: 'success',
    cancelled: 'error'
  }
  return variants[status] || 'muted'
}

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

const formatDate = (date) => {
  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 (error) {
    return t('ordersDetail.labels.dates_undefined')
  }
}

await loadTeamOrders()
</script>
