<template>
  <div class="productcard_container">
    <div class="row productcard_container-basic">
      <div class="image_container" :class="expanded ? 'col-md-5' : 'col-md-2'">
        <img
          v-if="product.image"
          class="image"
          :src="product.image"
          :alt="product.name"
        />
        <img
          v-else
          class="image"
          src="@/assets/img/latienda-product-default.svg"
          :alt="product.name"
        />
      </div>
      <div class="info_container" :class="expanded ? 'col-md-5' : 'col-md-6'">
        <h2 v-b-toggle="'collapse-' + product.id" variant="primary">
          {{ product.name }}
        </h2>
        <span v-if="product.price" class="price">{{
          `${product.price}€`
        }}</span>
        <span v-else class="price">Precio a consultar</span>
        <span v-if="Number(product.shipping_cost)"
          >| {{ `Gastos de envío ${product.shipping_cost}€` }}</span
        >
        <span v-else>| Sin gastos de envío</span>

        <span v-if="product.stock">| {{ `Stock ${product.stock}` }} </span>

        <div
          class="description"
          :class="{ 'not-expanded-description': !expanded }"
        >
          <p
            v-if="product.description"
            v-sanitize="[
              {
                allowedTags: ['p'],
                allowedAttributes: {},
              },
              product.description,
            ]"
          >
            <span v-if="product.shipping_terms">{{
              product.shipping_terms
            }}</span>
          </p>
        </div>
        <b-collapse :id="'collapse-' + product.id" accordion="my-accordion">
          <div class="tags_container">
            <NuxtLink
              :to="tagRoute(n)"
              class="tag_container"
              v-for="n in product.tags"
              :key="n"
            >
              <img
                alt="tag image"
                class="tag_img"
                src="@/assets/img/latienda-tag.svg"
              />
              <span>{{ n }}</span>
            </NuxtLink>
          </div>
          <div class="smlogos_container">
            <p class="share-text">Comparte:</p>
            <div class="smlogo_container">
              <a class="smlogo_link" @click="shareFacebook">
                <img
                  class="smlogo_img"
                  alt="facebook logo"
                  src="@/assets/img/latienda-smlogo-facebook.svg"
                />
              </a>
            </div>
            <!-- <a @click="shareTwitter"> -->
            <a :href="shareTwitter()">
              <div class="smlogo_container">
                <img
                  class="smlogo_img"
                  alt="twitter logo"
                  src="@/assets/img/latienda-smlogo-twitter.svg"
                />
              </div>
            </a>
            <a
              :href="shareWhatsApp()"
              data-action="share/whatsapp/share"
              target="_blank"
              title="latiendacoop"
            >
              <div class="smlogo_container">
                <img
                  alt="whatsapp logo"
                  class="smlogo_img"
                  src="@/assets/img/latienda-smlogo-whatsapp.svg"
                />
              </div>
            </a>
          </div>
          <div v-if="product.company" class="coop_info">
            <NuxtLink :to="`c/${product.company.id}`">
              <h2>{{ product.company.company_name }}</h2>
            </NuxtLink>
            <p>{{ product.company.description }}</p>
            <a :href="product.company.web_link">{{
              product.company.web_link
            }}</a>
          </div>
        </b-collapse>
      </div>
      <div
        :class="
          expanded
            ? 'col-md-2 button_container-detail'
            : 'col-md-4 button_container'
        "
        align="center"
      >
        <button
          @click="buyIntent"
          :class="expanded ? 'button_buy-simple' : 'button_buy'"
        >
          <img
            class="button_cart_img"
            alt="cart"
            src="@/assets/img/latienda-carrito.svg"
          />
          <span v-show="!expanded">Comprar</span>
        </button>
        <div
          v-if="product.discount && product.discount > 0"
          class="discount-tag"
        >
          {{ `Descuento ${product.discount}%` }}
        </div>
        <span v-if="product.company" v-show="!expanded">{{
          product.company.company_name
        }}</span>
      </div>
    </div>

    <div v-if="expanded && relatedProducts" class="related_products">
      <h2>Productos relacionados</h2>
      <ProductsRelated :relatedProducts="relatedProducts" />
    </div>
    <ProductModal v-if="modal" :product="product" @close="closeModal" />
  </div>
</template>

<script>
import { mapState } from 'pinia'
import ProductModal from './ProductModal.vue'
import ProductsRelated from './ProductsRelated.vue'
import socialShare from '~/utils/socialShare'
export default {
  components: { ProductsRelated, ProductModal },
  props: {
    product: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      expanded: false,
      modal: false,
      productUrl: null,
      relatedProducts: null,
    }
  },
  computed: {
    ...mapState(useAuthStore, ['access']),
  },
  mounted() {
    this.productUrl = window.location.origin + `/productos/${this.product.id}`

    this.$root.$on('bv::collapse::state', async (collapseId, isJustShown) => {
      if (collapseId === `collapse-${this.product.id}`) {
        this.expanded = isJustShown
        if (this.expanded) {
          await this.getRelatedProducts()
          await this.sendLog('view')
        }
      }
    })
  },

  methods: {
    tagRoute(tag) {
      return `/busqueda?tags=${tag}`
    },
    async getRelatedProducts() {
      try {
        const { data } = await this.$api.get(
          `/products/${this.product.id}/related/`
        )
        this.relatedProducts = data
      } catch {
        this.relatedProducts = null
      }
    },

    openUrl(url) {
      window.open(url)
    },

    buyIntent() {
      this.sendLog('shop')
      return this.product.url
        ? this.openUrl(this.product.url)
        : (this.modal = true)
    },

    async getPosition() {
      const geoLocation = () =>
        new Promise((resolve, reject) =>
          navigator.geolocation.getCurrentPosition(
            (posData) => {
              resolve(posData)
            },
            (error) => {
              reject(error)
            }
          )
        )
      try {
        const position = await geoLocation()
        const geo = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        }
        return geo
      } catch {
        const geo = null
        return geo
      }
    },

    async sendLog(action) {
      const geo = await this.getPosition()
      try {
        const config = useRuntimeConfig()
        const accessToken = this.access
        const data = await $fetch('https://api.ipify.org?format=json', {
          baseURL: config.public.baseURL,
          method: 'GET'
        })
        const ip = data.ip
        const object = {
          action: action,
          action_object: {
            model: 'product',
            id: this.product.id,
          },
        }
        if (ip) object.ip = ip
        if (geo) object.geo = geo
        //TODO: review problems with 406 error backend
        await $fetch(`/stats/me/`, {
          baseURL: config.public.baseURL,
          method: 'POST',
          body: object,
          headers: {
              Authorization: `Bearer ${accessToken}`
            }
        })
      } catch (error) {
        console.error('Error sending log:', error)
      }
    },

    closeModal(value) {
      this.modal = false
      if (value === 200) {
        this.$bvToast.toast(`Email enviado correctamente`, {
          title: 'latienda.coop',
          autoHideDelay: 5000,
          appendToast: true,
          variant: 'success',
        })
      } else if (value) {
        this.$bvToast.toast(`Se ha producido un error en el envío`, {
          title: 'latienda.coop',
          autoHideDelay: 5000,
          appendToast: true,
          variant: 'danger',
        })
      }
    },

    shareFacebook() {
      const url = socialShare.facebook(this.productUrl)
      window.open(url, '_blank')
    },
    shareTwitter() {
      return socialShare.twitter(this.productUrl)
    },
    shareWhatsApp() {
      return socialShare.whatsApp(this.productUrl)
    },
  },
}
</script>

<style lang="scss" scoped>
.productcard_container {
  border: 3px $color-grey-nav solid;
  border-radius: 5px;
  margin-bottom: 12px;
}
.productcard_container-basic {
  padding: 25px 20px;
}

.image_container {
  height: 100%;
  overflow: hidden;
  margin: auto;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info_container {
  h2 {
    outline: none;
    font-weight: $regular;
    color: $color-navy;
    font-size: $m;
  }
  .price {
    font-weight: $bold;
    color: $color-navy;
    font-size: $m;
  }
  span {
    color: $color-greytext;
  }
  .description {
    margin-top: 8px;
    font-family: $font-secondary;
    font-size: $s;
    color: $color-greytext;
  }
}

.not-expanded-description {
  display: -webkit-box;
  -webkit-line-clamp: 5;
  -webkit-box-orient: vertical;
  overflow: hidden;
  @include mobile {
    -webkit-line-clamp: 3;
  }
}

.button_container {
  display: flex;
  flex-direction: column;
  font-size: $m;

  span {
    margin-top: 15px;
    text-align: center;
    font-weight: medium;
    font-size: $m;
    color: $color-navy;
  }

  .button_buy {
    border: 3px solid $color-orange;
    border-radius: 5px;
    background-color: $color-light;

    &:hover {
      box-shadow: 0 4px 16px rgba(99, 99, 99, 0.2);
      transition: all 0.2s ease;
    }

    span {
      color: $color-orange;
      font-weight: $bold;
      display: inline-block;
      margin-bottom: 15px;
    }
  }
}

.button_buy-simple {
  border: 3px solid $color-orange;
  border-radius: 8px;
  background-color: $color-light;
  padding: 10px 20px;

  &:hover {
    box-shadow: 0 4px 16px rgba(99, 99, 99, 0.2);
    transition: all 0.2s ease;
  }

  .button_cart_img {
    margin-right: 0;
  }
}

.tag_container {
  margin: 25px 6px 0 0;
  border: 2px solid $color-greylayout;
  border-radius: 5px;
  padding: 6px 10px;
  display: inline-block;
  font-family: $font-secondary;
  font-size: $xs;
  color: $color-greytext;

  .tag_img {
    width: 18px;
  }
}

.discount-tag {
  margin: 5px;
  border: none;
  background-color: $color-green;
  border-radius: 5px;
  padding: 6px 10px;
  display: inline-block;
  font-family: $font-secondary;
  font-size: $xs;
  color: $color-greytext;
}

.share-text {
  color: $color-navy;
  font-size: $m;
  margin-top: 2rem;
  padding-bottom: 0.2em;
}

.smlogo_container {
  cursor: pointer;
  display: inline-block;
  margin-bottom: 0.5rem;

  .smlogo_img {
    width: 40px;
    fill: $color-greytext;
  }

  img:hover {
    transform: scale(1.1);
    transition: all 0.2s ease;
  }
}

.button_cart_img {
  width: 20px;
  margin-right: 10px;
}

.coop_info {
  margin-top: 25px;
  p,
  a {
    margin-top: 8px;
    font-family: $font-secondary;
    font-size: $s;
    color: $color-greytext;
  }
  a {
    text-decoration: underline;
  }
  p {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

.related_products {
  background-color: $color-lighter-green;
  text-align: center;
  padding: 0 15px;

  h2 {
    margin: 35px auto;
    font-weight: $regular;
    color: $color-navy;
    font-size: $m;
    display: inline-block;
  }
}

.content > h2,
h3,
p {
  margin: 0;
}
</style>
