<template>
  <UiContainer>
    <transition>
      <div v-if="showPopup && curImage" ref="dropdownRef" tabindex="0"
           class="fixed top-0 left-0 bg-[#000000cc] w-screen h-screen z-50 flex items-center justify-center cursor-pointer"
           @keyup.esc="showPopup = false" @keyup.left="goLeft" @keyup.right="goRight" @click.self="showPopup = false">
        <div class="border border-white p-4 rounded-2xl shadow-2xl bg-white cursor-auto">
          <img :src="`/api/public/file/${curImage}_l.webp`" class="max-h-[80vh] object-contain" alt=""
               @load="focusOnImgLoad">
        </div>
        <button class="absolute top-8 p-8 right-8 text-4xl rotate-45 text-white" @click="showPopup = false">
          +
        </button>
      </div>
    </transition>
    <div class="flex gap-[100px]">
      <div class="flex gap-[25px]">
        <div class="flex flex-col gap-[15px]">
          <div v-for="image in product.picture_uuids" :key="image" class="h-[100px] w-[90px] border border-button py-3 flex items-center justify-center rounded-[8px]"
               @click="curImage = image">
            <img :src="`/api/public/file/${image}_m.webp`" :alt="product.name" srcset="" class="h-full w-auto">
          </div>
        </div>
        <div class="cursor-pointer" @click="showPopup = true">
          <img :src="`/api/public/file/${curImage}_m.webp`" class="w-72" alt="">
        </div>
      </div>
      <!-- <div class="w-[70%]">
        <h1 class="font-bold text-2xl">
          {{ product.name }}
        </h1>
        <div>
          <span class="mx-4">Product reference:</span><span>{{ product.reference }}</span>
        </div>
        <div class="my-4" v-html="product.description" />
        <div class="my-12">
          <div class="text-2xl font-bold">
            <span class="mx-4">Price:</span><span>{{ formattedPrice }}</span>
          </div>
          <div class="">
            <span class="mx-4">Tax information:</span><span>{{ product.tax_name }}</span>
          </div>
          <div class="font-bold">
            <span class="mx-4">Buy out price:</span><span>{{ formattedBuyOutPrice }}</span>
          </div>

          <button :disabled="!product.sale_active"
            class="btn disabled:bg-gray-500 bg-button text-white px-4 py-4 rounded-2xl cursor-pointer"
            @click="productStore.incrementCartItem(product.id)">
            Add to cart
          </button>
        </div>
      </div> -->
      <div class="w-full space-y-[30px]">
        <div class="space-y-[15px]">
          <div class="flex items-center justify-between w-full">
            <h1 class="h4-uppercase-bold-inter max-w-[450px]">
              {{ product.name }}
            </h1>
            <button
              class="h-[40px] sm:h-[43px] px-[10px] sm:px-[17px] border border-gray dark:border-button-disabled text-gray dark:text-button-disabled hover:bg-gray transition-all hover:text-white rounded-[8px] cursor-pointer"
              @click="menuStore.navigateToItem()">
              {{ $t("back_to_home") }}
            </button>
          </div>
          <p class="text-button font-inter text-base leading-[150%] uppercase sm:text-[20px]">
            Title: {{
              product.reference }}
          </p>
        </div>
        <div class="flex flex-col gap-5" v-html="product.description" />
        <div class="flex items-end justify-between">
          <div class="">
            <h4
              class="text-accent-green-light font-inter text-[12px] sm:text-[21px] md:text-2xl leading-[150%] font-bold">
              {{ formattedPrice }}
            </h4>
            <p>{{ product.tax_name }}</p>
            <p>{{ formattedBuyOutPrice }}</p>
          </div>
          <div class="group flex cursor-pointer items-center justify-start gap-2 whitespace-nowrap">
            <button
              class="h-[40px] cursor-pointer min-w-40 rounded-[10px] px-[22px] transition-all sm:h-[50px] md:h-[65px] md:rounded-[15px] md:px-[42px] bg-button text-text-dark group-hover:bg-button-hover">
              Add to cart
            </button>
            <div :disabled="!product.sale_active" class="
              flex h-[40px] w-[40px] items-center justify-center rounded-[10px] p-2.5 transition-all sm:h-[50px] sm:w-[50px] md:h-[65px] md:w-[65px] md:rounded-[15px] bg-button text-text-dark group-hover:bg-button-hover
            " @click="productStore.incrementCartItem(product.id)">
              <svg class="" width="26" height="26" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M25.1274 1.87258C25.1274 1.3203 24.6797 0.872582 24.1274 0.872584L15.1274 0.872583C14.5751 0.872583 14.1274 1.3203 14.1274 1.87258C14.1274 2.42487 14.5751 2.87258 15.1274 2.87258L23.1274 2.87258L23.1274 10.8726C23.1274 11.4249 23.5751 11.8726 24.1274 11.8726C24.6797 11.8726 25.1274 11.4249 25.1274 10.8726L25.1274 1.87258ZM1.5 24.5L2.20711 25.2071L24.8345 2.57969L24.1274 1.87258L23.4203 1.16548L0.792893 23.7929L1.5 24.5Z"
                  fill="currentColor" />
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
  </UiContainer>

  <!-- <div>
    <UiContainer>
      <transition>
        <div v-if="showPopup && curImage" ref="dropdownRef" tabindex="0"
          class="fixed top-0 left-0 bg-[#000000cc] w-screen h-screen z-50 flex items-center justify-center cursor-pointer"
          @keyup.esc="showPopup = false" @keyup.left="goLeft" @keyup.right="goRight" @click.self="showPopup = false">
          <div class="border border-white p-4 rounded-2xl shadow-2xl bg-white cursor-auto">
            <img :src="`/api/public/file/${curImage}_l.webp`" class="max-h-[80vh] object-contain" alt=""
              @load="focusOnImgLoad">
          </div>
          <button class="absolute top-8 p-8 right-8 text-4xl rotate-45 text-white" @click="showPopup = false">
            +
          </button>
        </div>
      </transition>
      <div class="flex w-full gap-1">
        <div class="w-[50%] min-w-150px">
          <div class="flex gap-2">
            <div v-for="image in product.picture_uuids" :key="image" class="flex justify-center h-20 cursor-pointer"
              @click="curImage = image">
              <img :src="`/api/public/file/${image}_m.webp`" :alt="product.name" srcset="">
            </div>
            <div class="cursor-pointer" @click="showPopup = true">
              <img :src="`/api/public/file/${curImage}_m.webp`" class="w-72" alt="">
            </div>
          </div>
        </div>

        <div class="w-[50%]">
          <h1 class="font-bold text-2xl">
            {{ product.name }}
          </h1>
          <div>
            <span class="mx-4">Product reference:</span><span>{{ product.reference }}</span>
          </div>
          <div class="my-4" v-html="product.description" />
          <div class="my-12">
            <div class="text-2xl font-bold">
              <span class="mx-4">Price:</span><span>{{ formattedPrice }}</span>
            </div>
            <div class="">
              <span class="mx-4">Tax information:</span><span>{{ product.tax_name }}</span>
            </div>
            <div class="font-bold">
              <span class="mx-4">Buy out price:</span><span>{{ formattedBuyOutPrice }}</span>
            </div>

            <button :disabled="!product.sale_active"
              class="btn disabled:bg-gray-500 bg-button text-white px-4 py-4 rounded-2xl cursor-pointer"
              @click="productStore.incrementCartItem(product.id)">
              Add to cart
            </button>
          </div>
        </div>
      </div>
      <div class="flex gap-4">
        <div class="w-1/2 flex cursor-pointer">
          <div v-for="rel in product.recommendations" :key="rel.id">
            <nuxt-link :to="{
              name: `id-slug___${$i18n.locale}`,
              params: {
                id: menuStore.getProductMenu()?.id,
                slug: menuStore.getProductMenu()?.front_menu_lang[0]
                  .link_rewrite,
              },
              query: { prod_id: rel?.id, name: rel?.link_rewrite },
            }">
              <div class="w-1/3">
                {{ rel.name }}
                <img :src="`/api/public/file/${rel.cover_picture_uuid}_m.webp`" class="h-24" alt="">
              </div>
            </nuxt-link>
          </div>
        </div>
        <div class="w-1/2">
          <div v-for="feature in product.features" :key="feature.feature" class="flex gap-4 justify-around border-b">
            <span class="mx-4">{{ feature.feature }}:</span>
            <span class="mx-4">
              {{ feature.value }}
            </span>
          </div>
        </div>
      </div>
    </UiContainer>
  </div> -->
</template>

<script setup lang="ts">
import type { GenericResponse, ProductItem } from '~/types'

const menuStore = useMenuStore()
const { $session } = useNuxtApp()
const productStore = useProductStore()
const dropdownRef = ref()

// const addToCart = (p: ProductItem) => {
//     alert('add to cart product: ' + p.name)
// }

const formatPrice = (p: number) => {
  const formatdecimal = new Intl.NumberFormat(
    $session.cookieData.value.country.iso_code,
    {
      style: 'decimal',
      maximumFractionDigits: $session.cookieData.value.currency.precision,
    },
  ).format(p)
  return $session.cookieData.value.currency.suffix
    ? $session.cookieData.value.currency.sign + ' ' + formatdecimal
    : formatdecimal + ' ' + $session.cookieData.value.currency.sign
}

const focusOnImgLoad = () => {
  dropdownRef.value.focus()
}

const formattedPrice = computed(() => {
  return formatPrice(product.value.price)
})

const formattedBuyOutPrice = computed(() => {
  return formatPrice(product.value.buyout_price)
})

const route = useRoute()

// if (!route.query?.prod_id) {
//     throw createError({
//         statusCode: 404,
//         statusMessage: 'Not Found',
//         fatal: true
//     });
// }

const getProduct = async (): Promise<ProductItem> => {
  if (route.query?.prod_id) {
    const data = await useMyFetch<GenericResponse<ProductItem>>(
      `/api/public/product/${route.query?.prod_id}`,
      {},
    )
    // await new Promise(resolve => setTimeout(resolve, 200));
    return data.data
  }
  return {} as ProductItem
}

const product = ref(await getProduct())

watch(
  () => route.query?.prod_id,
  async () => {
    const data = await getProduct()
    product.value = data
    if (curImage.value != data.picture_uuids[0]) {
      curImage.value = data.cover_picture_uuid
    }
  },
)

watch($session.cookieData, async () => {
  const oldId = product.value.id
  const data = await getProduct()
  product.value = data
  if (oldId != data.id) {
    curImage.value = data.cover_picture_uuid
  }
})

const showPopup = ref(false)

const curImage = ref(product.value.cover_picture_uuid)

watch(showPopup, (newValue) => {
  if (newValue) {
    document.body.style.overflow = 'hidden'
  }
  else {
    document.body.style.overflow = 'unset'
  }
})

const goLeft = () => {
  if (!curImage.value) return
  const index = product.value.picture_uuids.indexOf(curImage.value)
  if (index > 0) {
    curImage.value = product.value.picture_uuids[index - 1]
  }
  else {
    curImage.value
      = product.value.picture_uuids[product.value.picture_uuids.length - 1]
  }
}

const goRight = () => {
  if (!curImage.value) return
  const index = product.value.picture_uuids.indexOf(curImage.value)
  if (index < product.value.picture_uuids.length - 1) {
    curImage.value = product.value.picture_uuids[index + 1]
  }
  else {
    curImage.value = product.value.picture_uuids[0]
  }
}
</script>

<style>
.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>
