<template>
  <div>
    <!-- breadcrumb start -->
    <breadcrumb
        :subtitle="$t('Search Page')"
        :title="propSearchText ? t('Search for (:search)', {search: propSearchText}) : $t('Search Page')"
    />
    <!-- breadcrumb end -->

    <!-- shop area start -->
    <section class="tp-shop-area pb-120">
      <div class="container">
        <div class="row">
          <div class="col-xl-12 col-lg-12">
            <div class="tp-shop-main-wrapper">
              <div v-if="displayedProducts.length" class="tp-shop-top mb-45">
                <div class="row">
                  <div class="col-xl-6">
                    <div class="tp-shop-top-left d-flex align-items-center">
                      <div class="tp-shop-top-result">
                        <p>
<!--                          {{ $t('Showing ') }}1–{{store.data?.slice(0, perView).length}}{{ $t(' of ') }}{{ data.length }}{{ $t(' results') }}-->
	                        {{
                            $t('Showing :count of :total results', {
                              count: perPage,
                              total: showingTotalLabel(),
                            })
                          }}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div class="col-xl-6">
                    <shop-sidebar-filter-select />
                  </div>
                </div>
              </div>

              <div class="tp-shop-items-wrapper tp-shop-item-primary">
                <div>
                  <div class="infinite-container">
	                  <div v-if="!pending" class="row">
					            <div v-if="!propSearchText.length || !displayedProducts.length" class="container">
						            <div v-if="!propSearchText.length" class="border rounded-0">
                          <form @submit.prevent="handleSubmit">
		                        <div class="tp-header-search-input-box-5">
		                            <div class="tp-header-search-input-5">
		                              <input
                                      v-model="searchText"
                                      :placeholder="$t('Search for products keywords ...')"
                                      type="text"
                                  >
		                              <span class="tp-header-search-icon-5">
		                                  <svg-search-2></svg-search-2>
		                              </span>
		                            </div>
		                            <button class="rounded-0" type="submit">{{ $t('Search') }}</button>
		                        </div>
		                      </form>
						            </div>
									      <div v-else class='text-center pt-50'>
									        <h5>{{ $t('No Products Found') }}</h5>
									        <nuxt-link class="tp-cart-checkout-btn mt-20" href="/">{{ $t('Back to Home') }}</nuxt-link>
									      </div>
					            </div>
	                    <div v-for="item in displayedProducts" v-else :key="item.id" class="col-xl-3 col-md-4 col-sm-6 infinite-item">
	                      <product-single :product="item" />
	                    </div>
	                  </div>
	                  <loading-skeleton v-else />
                  </div>
                </div>
              </div>
            </div>

            <div v-if="!pending" class="text-center">
<!--              <button
              		              v-if="
                                searchStore.products &&
                                perView < searchStore.products?.length
                              "
              		              class="btn-loadmore tp-btn tp-btn-border tp-btn-border-primary"
              		              type="button"
              		              @click="handlePerView"
                            >
              								{{ $t('Load More Products') }}
                            </button>
              <p v-else class="btn-loadmore-text">{{ $t('No More Products') }}</p>-->

              <div
                  v-if="showingPagination()"
                  class="tp-pagination"
              >
                <ui-laravel-pagination
                    :meta="meta || {}"
                    :data="filteredProducts || []"
                    :items-per-page="perPage"
                    :total="meta?.total"
                    @handle-paginate="handlePagination"
                />
              </div>
            </div>
            <loading-skeleton v-else />
          </div>
        </div>
      </div>
    </section>
    <!-- shop area end -->
  </div>
</template>

<script lang="ts" setup>
import {useProductFilterStore} from "@/pinia/useProductFilterStore";
import {useSearchStore} from "@/pinia/useSearchStore";
import type {IProduct} from "@/types/product-d-t";
import {calcEndIndexByStartIndex, calcPageByStartIndex, calcStartIndexByPage} from "@/services/calcPageService";
import type {IMeta} from "@/types/meta-d-t";
import type {ISiteSettings} from "@/types/site-settings-d-t";
import type {IFetchProductOptions, TProductDataWithPagination} from "@/types/fetch-product-options-d-t";
import {api} from "@/plugins/api";
import type {IProductResponse} from "@/types/product-response-d-t";
import {convertProductResponse} from "@/plugins/data/product-data";

const {t} = useI18n();
const route = useRoute();
const router = useRouter();
const $settings = useNuxtApp()?.$settings as ISiteSettings;

const {title} = useSiteSettings();
const store = useProductFilterStore();
const perPage = Number($settings.perPage);
const noImageUrl = $settings.noImageUrl;

const filteredProducts = ref<IProduct[]>([]);
const startIndex = ref<number>(0);
const endIndex = ref<number>(filteredProducts.value?.length!);
const meta = useState<IMeta>('search-meta', () => ({} as IMeta));
// const meta = computed(() => searchStore.meta);

const propSearchText = computed(() => String(router.currentRoute.value?.query?.searchText || "").trim());
const propPage = computed(() => Number(router.currentRoute.value?.query?.page || 1));
const page = computed(() => Math.ceil((startIndex.value + perPage) / perPage));
// const page = ref<number>(route?.query?.page || 1);
// const page = ref<number>(propPage.value);
const searchText = ref<string>(propSearchText.value);

const searchStore = useSearchStore();

const displayedProducts = computed(() => {
  if (filteredProducts.value?.length > perPage) {
    return filteredProducts.value.slice(startIndex.value, endIndex.value);
  }

  return filteredProducts.value;
});

function setTitle() {
  nextTick(function () {
    useSeoMeta({
      title: title(
          propSearchText.value ? t('Search for (:search)', {search: propSearchText.value}) : '',
          propPage.value
      )
    });
  });
}

function handlePagination(data: IProduct[], start: number, end?: number): void {
  end = end === undefined ? calcEndIndexByStartIndex(start, perPage) : end;
  filteredProducts.value = data;
  startIndex.value = start;
  endIndex.value = end;

  store.handlePageChange(start);
  store.setData(data);

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

const {data: searchData, pending, refresh} = useAsyncData(
    `search-products-${searchText.value || ''}`,
    // @ts-ignore
    () => {
      if(!propSearchText.value)
      {
        meta.value = {} as IMeta
        handlePagination([] as IProduct[], 0, 0)
        return [] as IProduct[];
      }

      let opt: IFetchProductOptions = {
        page: propPage.value,
        search: propSearchText.value,
        plain: true,
        pagination: true,
      };

      store.updateProductOptions(opt);
      return api.productData(opt)
          // @ts-ignore
          .then(({data, meta: $meta}: TProductDataWithPagination<IProduct[] | IProductResponse[]>) => {
            meta.value = $meta || {};
            data = (data || [] as IProductResponse[]).map((x: IProductResponse) => {
              return convertProductResponse(x, noImageUrl)
            });

            let _data: Number[] = [];
            return data.filter((x: IProduct) => {
              if (_data.includes(Number(x.id))) {
                return false
              }
              _data.push(Number(x.id));
              return true;
            })
          })
          .then((products: IProduct[]) => {
            if (process.client) {
              if (products.length === 0 && Number(opt?.page) > 1) {
                router.push({
                  query: {
                    ...router.currentRoute.value?.query,
                    page: "1",
                    l: "221"
                  }
                })

                return products;
              }

              handlePagination(products, 0, products.length)
            }

            return products;
          });
    },
    {
      watch: [
        route,
        // startIndex,
        // router.currentRoute,
        // page
      ],
      server: false, // optional,
      // immediate: false
    }
);

const showingStartLabel = () => meta.value?.from || (startIndex.value + 1) || 0;
const showingEndLabel = () => meta.value?.to || (startIndex.value + filteredProducts.value.slice(startIndex.value, endIndex.value)?.length) || 0;
const showingTotalLabel = () => meta.value?.total || filteredProducts.value?.length || 0;
const showingPagination = () => Number(meta.value?.total) > perPage || false;

const handleSubmit = () => {
  if (searchText.value) {
    if (searchText.value === propSearchText.value) {
      refresh();
      return false;
    }

    router.push({
      path: '/search',
      query: {
        ...route?.query,
        searchText: searchText.value
      }
    });
  } else {
    store.handleResetFilter();
    router.push(`/search`)
  }
}

onMounted(() => {
  if (process.client) {
    if (!pending.value) {
      if (searchData.value?.length) {
        if (searchData.value.length !== store.product_data.length) {
          store.setData(searchData.value);
        }
        if (searchData.value.length !== filteredProducts.value.length) {
          filteredProducts.value = searchData.value || [];
        }
      } else {
        if (searchData.value?.length === 0 && propPage.value > 0) {
          router.push({
            query: {
              ...route?.query,
              page: 1,
              l: 300,
            }
          })
        } else {
          refresh();
        }
      }
    }
  }
});

watch(
    () => [route.query, route.params/*, page*/],
    () => {
      if (process.client) {
        handlePagination(
            filteredProducts.value || [],
            calcStartIndexByPage(undefined, perPage)
        )
      }
    }
);
</script>
