<template>
  <div v-if="!pending && product">
      <!-- breadcrumb start -->
      <product-details-breadcrumb v-if="product?.id" :product="product" />
      <breadcrumb v-else :subtitle="propProduct" :title="propProduct" />
    <!-- breadcrumb end -->

    <!-- product details area start -->
      <product-details-area :product="product" />
    <!-- product details area end -->

    <!-- related products start -->
      <product-related :product="product" />
    <!-- related products end -->
  </div>
</template>

<script lang="ts" setup>
import {useProductStore} from "@/pinia/useProductStore";
import type {IProduct} from "@/types/product-d-t";
import toolsService from "@/services/toolsService";
import {api} from "@/plugins/api";
import {convertProductResponse} from "@/plugins/data/product-data";
import type {IProductResponse} from "@/types/product-response-d-t";
import type {ISiteSettings} from "@/types/site-settings-d-t";

const productStore = useProductStore();
const route = useRoute();
const router = useRouter();
const propProduct = computed(() => String(router.currentRoute.value?.params?.product));
const {title} = useSiteSettings();
const $settings = useNuxtApp()?.$settings as ISiteSettings;
const {noImageUrl, updateSlugOnLocale} = $settings;

function setTitle(p?: IProduct) {
  if (p && Object.keys(p).length) {
    nextTick(function () {
      useSeoMeta({
        title: title(toolsService.parseProductName(p, true)),
        // todo:
        description: p?.seo_description,
        keywords: p?.seo_keywords
      });
    });
  }
}

const {data: product, pending, error, refresh, execute} = useLazyAsyncData(
    `product_${propProduct?.value}`,
    async (): Promise<IProduct | null> => {
      if (product.value && product.value?.sku && propProduct.value !== product.value?.sku) {
        return null;
      }

      return api.productData({
        slug: propProduct?.value,
        plain: true
      })
          // @ts-ignore
          .then((data: IProduct[] | IProductResponse[]) => {
            data = ((data || []) as IProductResponse[]).map(x => convertProductResponse(x, noImageUrl));
            if (!data || data.length === 0) {
              return [{} as IProduct] as IProduct[];
            }

            productStore.setData(data);
            return data as IProduct[];
          })
          .then((data: IProduct[]) => (data?.[0] || {}) as IProduct)
          .then((data: IProduct) => {
            if (updateSlugOnLocale === true && (data?.sku && data?.sku !== propProduct.value)) {
              navigateTo({params: {product: data.sku}, query: route.query});
              return null;
            }

            if (data && data?.images?.length > 0) {
              productStore.handleImageActive(data.images[0]);
            }

            if (process.client) {
              setTitle(data)
            }

            // await refreshNuxtData([`product-${product?.id}-differents`, `product-${product?.id}-accessories`]);
            return data as IProduct;
          })
          .catch(e => {
            if (e?.response?.status === 404) {
              return {} as IProduct;
            }

            throw e;
          });
    },
    {
      // initialData: Promise.resolve(productStore.product_data?.[0] as IProduct),
      watch: [route],
      immediate: false
    }
);

await execute();

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

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

watch(
    () => router.currentRoute.value?.params,
    (n) => {
      if (product.value && product.value?.sku && propProduct.value !== product.value?.sku) {
        product.value = null;
        // refresh();
      }
    }
);
</script>
