<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>
      <UiBackHeader
        to="/orders"
        back-label="Назад к моим заказам"
        :title="`Заказ ${currentOrderCode}`"
      />

      <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>
