<template>
  <Section variant="plain">
    <Stack gap="6">
        <Heading :level="1">Заказ #{{ order?.name || route.params.id }}</Heading>

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

        <Card v-else-if="isLoadingOrder" tone="muted" padding="lg">
          <Stack align="center" justify="center" gap="3">
            <Spinner />
            <Text tone="muted">Загружаем детали заказа...</Text>
          </Stack>
        </Card>

        <template v-else>
          <Card padding="lg">
            <Stack gap="4">
              <Stack direction="row" gap="3" align="center" wrap>
                <Text weight="semibold">{{ order?.sourceLocationName }}</Text>
                <Text tone="muted">→</Text>
                <Text weight="semibold">{{ order?.destinationLocationName }}</Text>
              </Stack>
              <Grid :cols="1" :md="3" :gap="4">
                <Stack align="center" gap="1">
                  <Heading :level="3">{{ order?.orderLines?.[0]?.quantity || 0 }} {{ order?.orderLines?.[0]?.unit || 'тонн' }}</Heading>
                  <Text tone="muted">{{ order?.orderLines?.[0]?.productName || 'Товар' }}</Text>
                </Stack>
                <Stack align="center" gap="1">
                  <Heading :level="3">{{ formatPrice(order?.totalAmount) }}</Heading>
                  <Text tone="muted">{{ order?.currency }}</Text>
                </Stack>
                <Stack align="center" gap="1">
                  <Heading :level="3">{{ getOrderDuration() }}</Heading>
                  <Text tone="muted">дней доставки</Text>
                </Stack>
              </Grid>
            </Stack>
          </Card>

          <Card padding="lg">
            <Stack gap="4">
              <Heading :level="2">Этапы маршрута</Heading>
              <Stack v-if="order?.stages?.length" gap="3">
                <Card
                  v-for="stage in order.stages"
                  :key="stage.uuid"
                  padding="lg"
                  tone="muted"
                >
                  <Stack gap="3">
                    <Stack direction="row" align="center" justify="between">
                      <Stack gap="1">
                        <Heading :level="3" weight="semibold">{{ stage.name }}</Heading>
                        <Text tone="muted" size="base">{{ getStageDateRange(stage) }}</Text>
                      </Stack>
                      <Pill variant="outline">{{ stage.stageType }}</Pill>
                    </Stack>

                    <Grid :cols="1" :md="2" :gap="4">
                      <Stack gap="2">
                        <Heading :level="4" weight="semibold">Компании</Heading>
                        <Stack v-if="getCompaniesSummary(stage).length" gap="2">
                          <Stack
                            v-for="companySummary in getCompaniesSummary(stage)"
                            :key="companySummary.name"
                            direction="row"
                            align="center"
                            justify="between"
                          >
                            <Text weight="semibold">{{ companySummary.name }}</Text>
                            <Text tone="muted" size="base">
                              {{ companySummary.totalWeight || 0 }}т · {{ companySummary.tripsCount || 0 }} рейсов
                            </Text>
                          </Stack>
                        </Stack>
                        <Text v-else tone="muted">Компании не назначены</Text>
                      </Stack>

                      <Stack gap="2">
                        <Heading :level="4" weight="semibold">Маршрут этапа</Heading>
                        <RouteMap :stages="[stage]" :height="200" />
                      </Stack>
                    </Grid>
                  </Stack>
                </Card>
              </Stack>
              <Text v-else tone="muted">Этапы маршрута не определены</Text>
            </Stack>
          </Card>

          <Card padding="lg">
            <Stack gap="3">
              <Heading :level="2">Общая карта маршрута</Heading>
              <RouteMap :stages="order?.stages || []" />
            </Stack>
          </Card>

          <Card padding="lg">
            <Stack gap="3">
              <Heading :level="2">Timeline доставки</Heading>
              <GanttTimeline
                v-if="order?.stages"
                :stages="order.stages"
                :showLoading="showLoading"
                :showUnloading="showUnloading"
              />
              <Stack v-else align="center" justify="center" gap="2">
                <Text tone="muted">Нет данных для timeline</Text>
              </Stack>
            </Stack>
          </Card>
        </template>
      </Stack>
  </Section>
</template>

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

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

const localePath = useLocalePath()
const route = useRoute()
const { isAuthenticated } = useAuth()
const { execute } = useGraphQL()

const order = ref<any>(null)
const isLoadingOrder = ref(true)
const hasOrderError = ref(false)
const orderError = ref('')
const showLoading = ref(true)
const showUnloading = ref(true)

const loadOrder = async () => {
  try {
    isLoadingOrder.value = true
    hasOrderError.value = false
    const orderUuid = route.params.id as string
    const result = await execute(GetOrderDocument, { orderUuid }, 'team', 'orders')
    order.value = result.getOrder
  } catch (err: any) {
    hasOrderError.value = true
    orderError.value = err.message || 'Не удалось загрузить заказ'
  } finally {
    isLoadingOrder.value = false
  }
}

const formatPrice = (price) => {
  if (!price) return '0 ₽'
  return new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB',
    minimumFractionDigits: 0
  }).format(price)
}

const getCompaniesSummary = (stage) => {
  const companies = []
  if (stage.stageType === 'service' && stage.selectedCompany) {
    companies.push({
      name: stage.selectedCompany.name,
      totalWeight: 0,
      tripsCount: 0,
      company: stage.selectedCompany
    })
    return companies
  }

  if (stage.stageType === 'transport' && stage.trips?.length) {
    const companiesMap = new Map()
    stage.trips.forEach(trip => {
      const companyName = trip.company?.name || 'Компания не указана'
      const weight = trip.plannedWeight || 0
      if (companiesMap.has(companyName)) {
        const existing = companiesMap.get(companyName)
        existing.totalWeight += weight
        existing.tripsCount += 1
      } else {
        companiesMap.set(companyName, {
          name: companyName,
          totalWeight: weight,
          tripsCount: 1,
          company: trip.company
        })
      }
    })
    return Array.from(companiesMap.values())
  }
  return []
}

const getOrderDuration = () => {
  if (!order.value?.stages?.length) return 0
  let minDate = null
  let maxDate = null
  order.value.stages.forEach(stage => {
    stage.trips?.forEach(trip => {
      const startDate = new Date(trip.plannedLoadingDate || trip.actualLoadingDate)
      const endDate = new Date(trip.plannedUnloadingDate || trip.actualUnloadingDate)
      if (!minDate || startDate < minDate) minDate = startDate
      if (!maxDate || endDate > maxDate) maxDate = endDate
    })
  })
  if (!minDate || !maxDate) return 0
  const diffTime = Math.abs(maxDate - minDate)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

const getStageDateRange = (stage) => {
  if (!stage.trips?.length) return 'Даты не определены'
  let minDate = null
  let maxDate = null
  stage.trips.forEach(trip => {
    const startDate = new Date(trip.plannedLoadingDate || trip.actualLoadingDate)
    const endDate = new Date(trip.plannedUnloadingDate || trip.actualUnloadingDate)
    if (!minDate || startDate < minDate) minDate = startDate
    if (!maxDate || endDate > maxDate) maxDate = endDate
  })
  if (!minDate || !maxDate) return 'Даты не определены'
  const formatDate = (date) => date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
  if (minDate.toDateString() === maxDate.toDateString()) return formatDate(minDate)
  return `${formatDate(minDate)} - ${formatDate(maxDate)}`
}

onMounted(() => {
  if (isAuthenticated.value) {
    loadOrder()
  }
})
</script>
