<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import {
  OrderDetailDocument,
  type OrderDetailQuery,
} from '~/composables/graphql/generated';
import { formatOrderCode } from '~/composables/useOrderCodePresentation';
import {
  orderDeliveryStateText,
  orderLogisticsStateText,
} 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,
);

const currentOrderCode = computed(() => formatOrderCode(currentOrder.value?.code));
</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">{{ 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"
          />
        </div>

        <div class="surface-card rounded-3xl p-5">
          <h2 class="text-xl font-bold text-[#123824]">Доставка</h2>
          <div class="mt-4 space-y-4 text-sm text-[#123824]">
            <div class="space-y-1">
              <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Адрес</p>
              <p class="text-base font-semibold">{{ currentOrder.deliveryAddress || 'Адрес пока не указан' }}</p>
            </div>
            <div class="grid gap-4 border-t border-[#deebe4] pt-4 md:grid-cols-2">
              <div class="space-y-1">
                <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Комментарий по доставке</p>
                <p>{{ orderDeliveryStateText(currentOrder.deliveryTerms) }}</p>
              </div>
              <div class="space-y-1">
                <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Логистика</p>
                <p>{{ orderLogisticsStateText(currentOrder.deliveryFee) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </section>
</template>
