<template>
  <div class="tp-product-details-tab-nav tp-tab">
    <nav>
      <div id="navPresentationTab" class="nav nav-tabs justify-content-center p-relative tp-product-tab" role="tablist">
        <button
            id="nav-description-tab"
            aria-controls="nav-description"
            aria-selected="true"
            class="nav-link"
            data-bs-target="#nav-description"
            data-bs-toggle="tab"
            role="tab"
            type="button"
            @click="handleActiveMarker($event)"
        >{{ $t("Description") }}</button>

        <button
            id="nav-addInfo-tab"
            aria-controls="nav-addInfo"
            aria-selected="false"
            class="nav-link active"
            data-bs-target="#nav-addInfo"
            data-bs-toggle="tab"
            role="tab"
            type="button"
            @click="handleActiveMarker($event)"
        >{{ $t("Additional information") }}</button>

        <button
            id="nav-review-tab"
            aria-controls="nav-review"
            aria-selected="false"
            class="nav-link"
            data-bs-target="#nav-review"
            data-bs-toggle="tab"
            role="tab"
            type="button"
            @click="handleActiveMarker($event)"
        >{{ $t("Reviews (:count)", meta?.total || 0) }}</button>
        <span id="productTabMarker" class="tp-product-details-tab-line"></span>
      </div>
    </nav>
    <div id="navPresentationTabContent" class="tab-content">
      <div
          id="nav-description"
          aria-labelledby="nav-description-tab"
          class="tab-pane fade"
          role="tabpanel"
          tabindex="0"
      >
          <div class="tp-product-details-desc-wrapper pt-80">
            <div class="row justify-content-center">
                <div class="col-xl-10">
                  <div class="tp-product-details-desc-item pb-105">
                      <div class="row">
                        <div class="col-lg-12">
                            <div class="tp-product-details-desc-content pt-25">
                              <span>{{ toolsService.parseCategoryName(product?.parentCategory) }}</span>
                              <h3 class="tp-product-details-desc-title">{{ toolsService.parseProductName(product, true) }}</h3>
		                          <p v-html="product_description"></p>
                            </div>
                        </div>
                      </div>
                  </div>
                </div>
            </div>
          </div>
      </div>
      <div
          id="nav-addInfo"
          aria-labelledby="nav-addInfo-tab"
          class="tab-pane fade show active"
          role="tabpanel"
          tabindex="0"
      >
          <div class="tp-product-details-additional-info ">
            <div class="row justify-content-center">
                <div class="col-xl-10">
                  <table>
                      <tbody>
                        <tr v-for="(info,i) in productAddionals" :key="i">
                            <td>{{ info.key }}</td>
                            <td>{{ info.value }}</td>
                        </tr>
                      </tbody>
                  </table>
                </div>
            </div>
          </div>
      </div>
      <div id="nav-review" aria-labelledby="nav-review-tab" class="tab-pane fade" role="tabpanel" tabindex="0">
          <div class="tp-product-details-review-wrapper pt-60">
            <div class="row">
                <div
                    :class="{
									'col-lg-6': isLoggedIn(),
									'col-lg-12': !isLoggedIn()
                }"
                >
                  <div class="tp-product-details-review-statics">
                      <!-- number -->
                      <div class="tp-product-details-review-number d-inline-block mb-50 w-100">
                        <h3 class="tp-product-details-review-number-title">{{ $t('Customer reviews') }}</h3>
                        <div class="tp-product-details-review-summery d-flex align-items-center">
                            <div class="tp-product-details-review-summery-value">
                              <span>{{ product?.rating }}</span>
                            </div>
                            <div class="tp-product-details-review-summery-rating d-flex align-items-center">
										          <product-rating :product="product" />
                              <p>{{ $t(':count Reviews', {count: meta?.total || 0}) }}</p>
                            </div>
                        </div>
                        <div v-if="false" class="tp-product-details-review-rating-list">
                            <!-- rating item -->
                            <product-details-rating-item :star="5" width="82" />
                            <product-details-rating-item :star="4" width="30" />
                            <product-details-rating-item :star="3" width="15" />
                            <product-details-rating-item :star="2" width="6" />
                            <product-details-rating-item :star="1" width="10" />
                          <!-- end rating item -->
                        </div>
                      </div>

                    <!-- reviews -->
                      <div class="tp-product-details-review-list pr-110">
                        <h3 class="tp-product-details-review-title">{{ $t('Rating & Review') }}</h3>
                        <div v-if="reviews?.length > 0">
                          <div
                              v-for="(item,i) in reviews"
                              :key="item?.id || i"
                              class="tp-product-details-review-avater d-flex align-items-start"
                          >
                              <div class="tp-product-details-review-avater-thumb">
                                <a href="#">
                                    <img :src="toolsService.parseImageUrl(item?.photo)" alt="user profile image">
                                </a>
                              </div>
                              <div class="tp-product-details-review-avater-content">
                                <div class="tp-product-details-review-avater-rating d-flex align-items-center">
                                    <product-rating :product="item" />
                                </div>
                                <h3 class="tp-product-details-review-avater-title">{{ item.user }}</h3>
                                <span class="tp-product-details-review-avater-meta">{{ item.date }} </span>

                                <div class="tp-product-details-review-avater-comment">
                                    <p>{{ item.comment || '-' }}</p>
                                </div>
                              </div>
                          </div>

        <div class="text-center">
          <button
              :disabled="reviewsPending"
              aria-selected="false"
              class="tp-logout-btn w-100"
              role="button"
              type="button"
              @click="handleViewMore"
          >{{ $t('See more') }}</button>
        </div>
                        </div>
                        <div v-else>
                          <h5>{{ $t('No Reviews Found') }}</h5>
                        </div>
                      </div>
                  </div>
                </div> <!-- end col -->
                <div v-if="isLoggedIn()" class="col-lg-6">
                  <div class="tp-product-details-review-form">
                      <h3 class="tp-product-details-review-form-title">{{ $t('Review this product') }}</h3>
                      <p>{{ $t('All fields are Required') }}</p>
                    <!-- form start -->
                     <forms-review-form :product="product" @added="handleAddReview($event)" />
                    <!-- form end -->
                  </div>
                </div>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {type IProduct} from '@/types/product-d-t';
import toolsService from "@/services/toolsService";
import {useUserStore} from "@/pinia/useUserStore";
import {api} from "@/plugins/api";
import type {IReview} from "@/types/review-d-t";
import {convertProductReviewResponse} from "@/plugins/data/product-reviews-data";
import type {TPaginationOr} from "@/types/pagination-d-t";
import type {IReviewResponse} from "@/types/review-response-d-t";
import type {IMeta} from "@/types/meta-d-t";

const {isLoggedIn, user} = useUserStore();
const props = defineProps<{ product: IProduct; mainProduct?: IProduct }>();
const route = useRoute();

interface IDataPerPage {
  [pageNum: string | number]: IReview[]
}

interface IDataPerProduct {
  [pid: string | number]: IDataPerPage[] | IReview[]
}

const _dataPerPage = ref<IDataPerPage[] | IDataPerProduct[]>([]);
const page = ref(1);
// const _data = ref<{ [key: string]: IReview[] }>([]);
const _data = ref<Number[]>([]);
const reviews = ref<IReview[]>([]);
const product_description = computed(() => toolsService.normalizeLineEndingsToHtml(props.product?.description));
const pId = computed<Number>(() => Number(props.mainProduct?.id || props.product.id || 0));
const meta = useState<IMeta>('meta', () => ({} as IMeta));

const loadData = (): Promise<IReview[]> | IReview[] => {
  if (_dataPerPage.value?.[Number(pId.value)]?.[page.value - 1]) {
    return reviews.value;
  }

  return api.productReviewsData({
    product: props?.product,
    page: page.value,
    plain: true,
    pagination: true,
  })
      // @ts-ignore
      .then(({data, meta: $meta}: TPaginationOr<(IReview | IReviewResponse)[]>) => {
        meta.value = $meta;
        data = data.map((x: IReviewResponse) => convertProductReviewResponse(x));

        let _data: Number[] = [];
        return data.filter((x: IReview) => {
          if (_data.includes(Number(x.id))) {
            return false
          }
          _data.push(Number(x.id));
          return true;
        }) as IReview[]
      })
      .then((data: IReview[]) => {
        if (!data.length) {
          page.value--;
          return reviews.value;
        }
        // @ts-ignore
        _dataPerPage.value[Number(pId.value)] = [...(_dataPerPage.value?.[Number(pId.value)] || [])]
        _dataPerPage.value[Number(pId.value)][page.value - 1] = [...data];
        // @ts-ignore
        reviews.value = _dataPerPage.value[Number(pId.value)].flat();

        return reviews.value;
      });
}

const {
  data: reviewsData,
  error: reviewsError,
  pending: reviewsPending,
  execute: executeReviews,
  refresh: reviewsRefresh,
} = useLazyAsyncData(
    `products-${pId.value}-reviews`,
    // @ts-ignore
    loadData,
    {
      watch: [pId],
      immediate: false
    }
)

const {
  data: productAddionals,
  pending: pendingAddionals,
  error: errorAddionals,
  refresh: refreshAddionals,
  execute: executeAddionals
} = useLazyAsyncData(
    `product_${props?.product?.id}_addionals`,
    () => {
      return api.productAddionalsData({
        slug: props?.product?.sku,
        plain: true
      })
    },
    {
      watch: [route],
      immediate: false
    }
);
await executeAddionals();

const handleViewMore = async () => {
  page.value++;
  await executeReviews();
}

const handleAddReview = (review: IReview) => {
  page.value = 1;
  // @ts-ignore
  _dataPerPage.value[Number(pId.value)] = []
  executeReviews();
  // reviews.unshift($event)
}

onMounted(() => {
  executeReviews();
  const nav_active = document.getElementById("nav-addInfo-tab");
  const marker = document.getElementById("productTabMarker");
  if (nav_active?.classList.contains("active") && marker) {
    marker.style.left = nav_active.offsetLeft + "px";
    marker.style.width = nav_active.offsetWidth + "px";
  }
  // loadData();
  // todo: handle additional info
});

const handleActiveMarker = (event: MouseEvent) => {
  const marker = document.getElementById("productTabMarker");
  if (marker && event.target) {
    marker.style.left = (event.target as HTMLButtonElement).offsetLeft + "px";
    marker.style.width = (event.target as HTMLButtonElement).offsetWidth + "px";
  }
};

watch(
    () => pId,
    (newStatus, oldStatus) => {
      page.value = 1;
      _data.value = [];
      reviewsRefresh();
      const nav_active = document.getElementById("nav-addInfo-tab");
      const marker = document.getElementById("productTabMarker");
      if (nav_active?.classList.contains("active") && marker) {
        marker.style.left = nav_active.offsetLeft + "px";
        marker.style.width = nav_active.offsetWidth + "px";
      }

    }
);

</script>
