<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="flex flex-wrap items-center gap-3 px-1">
        <NuxtLink
          to="/orders"
          aria-label="Назад к моим заказам"
          class="flex h-11 w-11 items-center justify-center rounded-full bg-white/70 text-[#0d854a] transition hover:bg-white"
        >
          <svg class="h-5 w-5" viewBox="0 0 20 20" fill="none">
            <path d="M11.5 4.5L6 10L11.5 15.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
          </svg>
        </NuxtLink>
        <h1 class="text-2xl font-black tracking-[-0.03em] text-[#123824] md:text-3xl">
          Заказ {{ currentOrderCode }}
        </h1>
      </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>
