<template>
  <div>
      <!-- breadcrumb start -->
      <breadcrumb v-if="!pendingOrder" :subtitle="getOrderTitle()" :title="getOrderTitle()" />
    <!-- breadcrumb end -->

    <!-- order area start -->
      <order-area v-if="!pendingOrder" :order="order" />
    <!-- order area end -->
  </div>
</template>

<script lang="ts" setup>
import {api} from "@/plugins/api";
import {convertUserOrdersResponse} from "@/plugins/data/user-orders-data";
import type {IUserOrder} from "@/types/user-order-d-t";
import {useUserStore} from "@/pinia/useUserStore";
import type {IUserOrderResponse} from "@/types/user-order-response-d-t";
import type {ISiteSettings} from "@/types/site-settings-d-t";

const route = useRoute();
const router = useRouter();
const propOrder = computed(() => String(router.currentRoute.value?.params?.order));
const {title} = useSiteSettings();
const $settings = useNuxtApp()?.$settings as ISiteSettings;
// const {noImageUrl, updateSlugOnLocale} = $settings;
const {t} = useI18n();

useUserStore().needUser();

useSeoMeta({title: title(t("Order Details"))});

function getOrderTitle(o?: IUserOrder|null) {
  o = o || order?.value;

  return o && o?.id ? t('Order :id Details', {id: o?.id}) : t('Order Details')
}

function setTitle(p?: IUserOrder | null) {
  if (p && Object.keys(p).length) {
    nextTick(function () {
      useSeoMeta({
        title: title(getOrderTitle(p)),
        // todo:
        // description: p?.seo_description,
        // keywords: p?.seo_keywords
      });
    });
  }
}

const {data: order, pending: pendingOrder, error, refresh, execute: executeOrder} = useAsyncData<IUserOrder>(
    `order_${propOrder?.value}`,
    async (): Promise<IUserOrder> => {
      if (order.value && order.value?.id && propOrder.value !== String(order.value?.id)) {
        return {} as IUserOrder;
      }

      return api.userOrdersData({id: propOrder?.value, plain: true})
          // @ts-ignore
          .then((data: IUserOrderResponse[]) => {
            data = (data && Array.isArray(data) ? data : [data]).map(x => convertUserOrdersResponse(x));

            if (!data || data.length === 0) {
              return [[]];
            }

            return data as IUserOrder[];
          })
          .then(data => data?.[0] as IUserOrder)
          .then((data: IUserOrder) => {
            if (process.client) {
              setTitle(data)
            }

            return data as IUserOrder;
          })
          .catch(e => {
            if (e?.response?.status === 404) {
              return {} as IUserOrder;
            }

            throw e;
          });
    },
    {
      // initialData: () => [],
      watch: [route],
      immediate: false
    }
);

await executeOrder();

if (order.value && order.value?.id) {
  setTitle(order.value)
}

if (
    (error?.value && error?.value?.message === 'EMPTY')
    // || !(order?.value && order?.value?.id)
) {
  showError({
    statusCode: 404,
    statusMessage: useI18n().t('Order not found'),
    data: 'EMPTY',
    error: error?.value || new Error('EMPTY'),
    fatal: true
  } as any);
}

watch(
    () => router.currentRoute.value?.params,
    (n) => {
      if (order.value && order.value?.id && propOrder.value !== String(order.value?.id)) {
        order.value = {} as IUserOrder;
        // refresh();
      }
    }
);

</script>
