<template>
  <Stack gap="6">
    <Heading :level="1">Мои заказы</Heading>

    <Alert v-if="hasError" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">Ошибка</Heading>
        <Text tone="muted">{{ error }}</Text>
        <Button @click="loadTeamOrders">Попробовать снова</Button>
      </Stack>
    </Alert>

    <Stack v-else-if="isLoading" align="center" justify="center" gap="3">
      <Spinner />
      <Text tone="muted">Загружаем заказы...</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 hover:shadow-md transition-shadow" @click="openOrder(order)">
          <Stack gap="3">
            <Stack direction="row" justify="between" align="center">
              <Heading :level="3">#{{ order.name }}</Heading>
              <Text tone="muted">{{ getOrderStartDate(order) }} → {{ getOrderEndDate(order) }}</Text>
            </Stack>

            <Grid :cols="1" :md="3" :gap="3">
              <Stack gap="1">
                <Text size="base" weight="semibold">Маршрут</Text>
                <Text tone="muted">{{ order.sourceLocationName }} → {{ order.destinationLocationName }}</Text>
              </Stack>

              <Stack gap="1">
                <Text size="base" weight="semibold">Товар</Text>
                <Text tone="muted">
                  {{ order.orderLines?.[0]?.productName || 'Загрузка...' }}
                  <template v-if="order.orderLines?.length > 1">
                    +{{ order.orderLines.length - 1 }} ещё
                  </template>
                </Text>
                <Text tone="muted" size="base">
                  {{ order.orderLines?.[0]?.quantity || 0 }} {{ order.orderLines?.[0]?.unit || 'тонн' }}
                </Text>
              </Stack>

              <Stack gap="1">
                <Text size="base" weight="semibold">Статус</Text>
                <Text tone="muted">{{ getStatusText(order.status) }}</Text>
                <Text tone="muted">Этапов завершено: {{ getCompletedStages(order) }} / {{ order.stages?.length || 0 }}</Text>
              </Stack>
            </Grid>
          </Stack>
        </Card>
      </Stack>

      <Stack v-else align="center" gap="3">
        <IconCircle tone="primary">
          <Icon name="lucide:shopping-bag" size="24" />
        </IconCircle>
        <Heading :level="3">Нет заказов</Heading>
        <Text tone="muted">Начните с создания нового расчета</Text>
        <Button @click="navigateTo(localePath('/dashboard'))">
          Создать новый расчет
        </Button>
      </Stack>
    </template>
  </Stack>
</template>

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

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

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

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 result = await execute(GetTeamOrdersDocument, {}, 'team', 'orders')
    orders.value = result.getTeamOrders || []
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || 'Не удалось загрузить заказы'
    orders.value = []
  } finally {
    isLoading.value = false
  }
}

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

const getOrderStartDate = (order: any) => {
  if (!order.createdAt) return 'Не указано'
  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.toISOString())
  if (order.createdAt) {
    const fallbackDate = new Date(order.createdAt)
    fallbackDate.setMonth(fallbackDate.getMonth() + 1)
    return formatDate(fallbackDate.toISOString())
  }
  return 'Не указано'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: 'Ожидает',
    processing: 'Обработка',
    in_transit: 'В пути',
    delivered: 'Доставлен',
    cancelled: 'Отменен'
  }
  return texts[status] || status || 'Неизвестно'
}

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 'Нет данных'
  try {
    const dateObj = new Date(date)
    if (isNaN(dateObj.getTime())) return 'Невалидная дата'
    return new Intl.DateTimeFormat('ru-RU', {
      day: 'numeric',
      month: 'long',
      year: 'numeric'
    }).format(dateObj)
  } catch {
    return 'Невалидная дата'
  }
}

onMounted(async () => {
  await loadTeamOrders()
})
</script>
