<script setup lang="ts">
import { useMutation, useQuery } from '@vue/apollo-composable';
import {
  BlockOrderDocument,
  CompleteOrderDocument,
  ManagerFinalizeOrderDocument,
  ManagerOrdersDocument,
  StartOrderWorkDocument,
} from '~/composables/graphql/generated';
import {
  orderDeliveryStateText,
  orderLineStateText,
} from '~/composables/useOrderDetailPresentation';

definePageMeta({
  middleware: ['manager-only'],
});

const route = useRoute();
const orderId = computed(() => String(route.params.id || ''));

const ordersQuery = useQuery(ManagerOrdersDocument, { status: null });

const finalizeMutation = useMutation(ManagerFinalizeOrderDocument);
const blockMutation = useMutation(BlockOrderDocument);
const startWorkMutation = useMutation(StartOrderWorkDocument);
const completeWorkMutation = useMutation(CompleteOrderDocument);

const currentOrder = computed(() =>
  (ordersQuery.result.value?.managerOrders ?? []).find((item) => item.id === orderId.value),
);

async function refetchOrder() {
  await ordersQuery.refetch({ status: null });
}

async function approveOrder() {
  if (!currentOrder.value) {
    return;
  }

  await finalizeMutation.mutate({ orderId: currentOrder.value.id, decision: 'APPROVE' });
  await refetchOrder();
}

async function rejectOrder() {
  if (!currentOrder.value) {
    return;
  }

  await finalizeMutation.mutate({ orderId: currentOrder.value.id, decision: 'REJECT' });
  await refetchOrder();
}

async function blockOrder() {
  if (!currentOrder.value) {
    return;
  }

  await blockMutation.mutate({
    input: {
      orderId: currentOrder.value.id,
      reason: 'Нужно уточнение параметров заказа.',
    },
  });
  await refetchOrder();
}

async function startOrder() {
  if (!currentOrder.value) {
    return;
  }

  await startWorkMutation.mutate({ orderId: currentOrder.value.id });
  await refetchOrder();
}

async function completeOrder() {
  if (!currentOrder.value) {
    return;
  }

  await completeWorkMutation.mutate({ orderId: currentOrder.value.id });
  await refetchOrder();
}
</script>

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

    <div v-if="ordersQuery.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"
        />

        <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(currentOrder.totalPrice) }}</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>
        </div>

        <div class="surface-card rounded-3xl p-5">
          <div class="flex flex-wrap items-center justify-between gap-3">
            <h2 class="text-xl font-bold text-[#123824]">Действия менеджера</h2>
            <div class="flex flex-wrap gap-2">
              <button class="btn btn-success btn-sm border-0" @click="approveOrder">Подтвердить</button>
              <button class="btn btn-error btn-sm border-0" @click="rejectOrder">Отклонить</button>
              <button class="btn btn-warning btn-sm border-0" @click="blockOrder">Заблокировать</button>
              <button class="btn btn-accent btn-sm border-0" :disabled="currentOrder.status !== 'CONFIRMED'" @click="startOrder">В работу</button>
              <button class="btn btn-neutral btn-sm border-0" :disabled="currentOrder.status !== 'IN_PROGRESS'" @click="completeOrder">Завершить</button>
            </div>
          </div>
        </div>
      </div>
    </template>
  </section>
</template>
