<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import {
  OrderDetailDocument,
  type OrderDetailQuery,
} from '~/composables/graphql/generated';
import {
  orderLogisticsStateText,
  orderDeliveryStateText,
  orderLineStateText,
} from '~/composables/useOrderDetailPresentation';

type OrderItem = NonNullable<OrderDetailQuery['order']>;

const route = useRoute();
const orderId = computed(() => String(route.params.id || ''));
const orderQuery = useQuery(OrderDetailDocument, () => ({
  id: orderId.value,
}));

const currentOrder = computed<OrderItem | null>(() =>
  orderQuery.result.value?.order ?? null,
);
</script>

<template>
  <section class="space-y-6">
    <NuxtLink to="/orders" class="text-sm font-semibold text-[#0d854a]">← Назад к моим заказам</NuxtLink>

    <div v-if="orderQuery.loading.value" class="manager-empty-state">
      Загружаем заказ...
    </div>

    <div v-else-if="!currentOrder" class="manager-empty-state">
      Заказ не найден.
    </div>

    <template v-else>
      <div class="manager-hero">
        <p class="manager-eyebrow">Заказ</p>
        <h1 class="manager-title">{{ currentOrder.code }}</h1>
      </div>

      <div class="space-y-4">
        <OrdersOrderStatusTimelineCard
          :status="currentOrder.status"
          :created-at="currentOrder.createdAt"
          audience="client"
        />

        <div class="surface-card rounded-3xl p-5">
          <h2 class="text-xl font-bold text-[#123824]">Состав заказа</h2>
          <ul class="mt-4 space-y-3">
            <li
              v-for="item in currentOrder.items"
              :key="item.id"
              class="manager-mini-card space-y-2"
            >
              <p class="text-sm font-semibold text-[#123824]">{{ item.productName }} × {{ item.quantity }}</p>
              <p class="text-sm text-[#5c7b69]">{{ orderLineStateText(item.unitPrice, item.lineTotal) }}</p>
            </li>
          </ul>
        </div>

        <div class="surface-card rounded-3xl p-5">
          <h2 class="text-xl font-bold text-[#123824]">Доставка</h2>
          <div class="mt-4 space-y-3">
            <div class="manager-mini-card text-sm text-[#123824]">
              Адрес: {{ currentOrder.deliveryAddress || 'Адрес пока не указан' }}
            </div>
            <div class="manager-mini-card text-sm text-[#123824]">
              {{ orderDeliveryStateText(currentOrder.deliveryTerms) }}
            </div>
            <div class="manager-mini-card text-sm text-[#123824]">
              {{ orderLogisticsStateText(currentOrder.deliveryFee) }}
            </div>
          </div>
        </div>
      </div>
    </template>
  </section>
</template>
