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

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,
);

const currentOrderCode = computed(() => formatOrderCode(currentOrder.value?.code));
</script>

<template>
  <section class="space-y-6">
    <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="surface-card rounded-3xl px-5 py-4">
        <div class="flex flex-wrap items-center gap-3">
          <NuxtLink to="/orders" class="text-sm font-semibold text-[#0d854a]">
            ← Назад к моим заказам
          </NuxtLink>
          <span class="hidden h-4 w-px bg-[#d8e4dd] md:block" />
          <span class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">
            Заказ
          </span>
          <span class="text-lg font-black tracking-[-0.03em] text-[#123824]">
            {{ currentOrderCode }}
          </span>
        </div>
      </div>

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

        <div>
          <h2 class="text-xl font-bold text-[#123824]">Состав заказа</h2>
          <OrdersOrderItemsTable
            class="mt-4"
            :items="currentOrder.items"
            :calculation-payload="currentOrder.calculationPayload"
            :framed="false"
          />
          <OrdersOrderDeliveryLine
            class="mt-3"
            :delivery-address="currentOrder.deliveryAddress"
            :delivery-terms="currentOrder.deliveryTerms"
            :delivery-fee="currentOrder.deliveryFee"
          />
        </div>
      </div>
    </template>
  </section>
</template>
