<template>
  <div class="container">
    <div class="row c-description">
      <div class="col-md-4">
        <div class="c-image-container">
          <img v-if="coop?.logo" :src="coop?.logo" alt="" />
          <img v-else src="@/assets/img/latienda-product-default.svg" alt="" />
        </div>
      </div>
      <div class="col-md-6">
        <h1 class="coop-name">{{ coop?.company_name }}</h1>
        <p class="coop-text">
          {{ coop?.description }}
        </p>
        <div class="tags_container">
          <NuxtLink
            v-for="n in coop?.tags"
            :key="n"
            :to="tagRoute(n)"
            class="tag_container"
          >
            <img class="tag_img" src="@/assets/img/latienda-tag.svg" />
            <span>{{ n }}</span>
          </NuxtLink>
        </div>
      </div>
    </div>
    <div class="row coop-links">
      <div class="col-md-4">
        <BButton
          v-if="coop?.shop_link"
          class="div-link"
          align="center"
          :href="coop?.shop_link"
          target="_blank"
        >
          <img class="div-link-img" src="@/assets/img/latienda-tienda.svg" />
          <span>Tienda online</span>
        </BButton>
        <BButton
          v-if="coop?.web_link"
          class="div-link"
          align="center"
          :href="coop?.web_link"
          target="_blank"
        >
          <img class="div-link-img" src="@/assets/img/latienda-web.svg" />
          <span>Página web</span>
        </BButton>
      </div>
      <div class="col-md-4">
        <div v-if="coop?.mobile || coop?.phone" class="div-action tel">
          <img
            class="div-action-img"
            src="@/assets/img/latienda-telefono.svg"
          />
          <span
            >{{ coop?.phone }} <br />
            {{ coop?.mobile }}</span
          >
        </div>
        <div v-if="coop?.email" class="div-action mail">
          <img class="div-action-img" src="@/assets/img/latienda-email.svg" />
          <span>{{ coop?.email }}</span>
        </div>
      </div>
      <div class="col-md-4">
        <div v-if="coop?.address" class="div-action address">
          <img class="div-action-img" src="@/assets/img/latienda-casa.svg" />
          <span>{{ coop?.address }}</span>
        </div>
        <div v-if="coop?.city" class="div-action location">
          <img
            class="div-action-img"
            src="@/assets/img/latienda-ubicacion.svg"
          />
          <span>{{ coop?.city }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-12 c-tabs">
        <div>
          <BCard no-body>
            <BTabs card>
              <BTab title="Devoluciones, garantías y reembolsos" active>
                <BCardText>
                  {{
                    coop?.sale_terms ||
                    'Consultar con la cooperativa para más información'
                  }}
                </BCardText>
              </BTab>
              <BTab title="Envío">
                <BCardText>
                  {{
                    coop?.shipping_terms ||
                    'Consultar con la cooperativa para más información'
                  }}
                </BCardText>
              </BTab>
            </BTabs>
          </BCard>
        </div>
      </div>
    </div>
    <div v-if="slicedProducts.length !== 0">
      {{ slicedProducts }} productos encontrados
      <div v-for="product in slicedProducts" :key="product.id">
        <ProductCard :key="product.key" :product="product" />
      </div>
      <BPagination
        v-model="currentPage"
        :v-if="products"
        class="pagination"
        :total-rows="rows"
        :per-page="perPage"
      />
    </div>
  </div>
</template>

<script>
import { mapState } from 'pinia'
export default {
  setup(){
    definePageMeta({
      layout: 'main',
    })
  },
  //TODO: implement head() method
  // head() {
  //   return {
  //     title: `latienda.coop | ${this.coop?.company_name}`,
  //     meta: [
  //       {
  //         hid: 'description',
  //         name: 'description',
  //         content: this.coop?.description,
  //       },
  //       { property: 'og:title', content: this.coop?.company_name },
  //       { property: 'og:description', content: this.coop?.description },
  //       { property: 'og:image', content: this.coop?.logo },
  //       { property: 'og:url', content: this.coop?.web_link },
  //       { name: 'twitter:card', content: 'summary_large_image' },
  //     ],
  //   }
  // },
  data() {
    return {
      coop: null,
      products: null,
      currentPage: 1,
      perPage: 10,
    }
  },
  computed: {
    ...mapState(useAuthStore, ['id', 'access']),
    rows() {
      return this.products?.length
    },
    slicedProducts() {
      const initial = (this.currentPage - 1) * this.perPage
      const final = this.currentPage * this.perPage
      const items = this.products ? this.products?.slice(initial, final) : []
      return items
    },
  },

  async created() {
    try {
      const config = useRuntimeConfig()
      const $route = useRoute()
      this.coop  = await $fetch(`/companies/${$route.params.id}/`,
        {
          baseURL: config.public.baseURL,
          method: 'GET',
        }
      )
      this.products = await $fetch(
        `/products?company=${route.params.id}`,
        {
          baseURL: config.public.baseURL,
          method: 'GET',
        }
      )

    } catch (error) {
      console.error(error)
    }
  },

  mounted() {
    this.sendLog('view')
  },

  methods: {
    tagRoute(tag) {
      return `/busqueda?tags=${tag}`
    },
    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: 'company',
            id: this.coop?.id,
          },
        }
        //console.log('Sending log OBJECT:', object)
        if (ip) object.ip = ip
        if (geo) object.geo = geo
        try {
          //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 /stats:', error)
        }
      } catch (error) {
        console.error('Error sending log:', error)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
//global classes for Bootstrap styling
ul.nav > li.nav-item {
  font-weight: bolder;
  :hover {
    color: $color-navy;
  }
  .active {
    border-top: 4px solid $color-navy;
    color: $color-navy;
  }
}
</style>

<style lang="scss" scoped>
.container {
  margin-top: 80px;
  margin-bottom: 80px;

  @include mobile {
    padding: 0.4em 2em;
  }
}

.c-description {
  margin-top: 40px;
  margin-bottom: 40px;
  @include mobile {
    margin-bottom: 0;
  }
}

.coop-links {
  margin-bottom: 40px;

  .div-action {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-left: 8px;
    overflow: hidden;

    .img-tel {
      width: 16px;
    }
  }

  .div-link-img,
  .div-action-img {
    width: 20px;
    margin-right: 8px;
  }

  .div-action-img {
    margin-left: 5px;
  }
}

.c-image-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  img {
    width: 100%;
    height: auto;
    object-fit: cover;
  }
}

.coop-name {
  font-size: $xl;
  color: $color-navy;
  text-transform: capitalize;
}
.coop-text {
  margin-top: 8px;
  font-family: $font-secondary;
  font-size: $s;
  color: $color-greytext;
}

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

.div-link {
  width: 100%;
  border: 3px solid $color-orange;
  border-radius: 5px;
  background-color: $color-light;
  font-weight: $bold;
  padding: 15px 0;
  margin-bottom: 5px;

  span {
    color: $color-orange;
  }
}

.div-action {
  width: 100%;
  background-color: $color-grey-nav;
  border: none;
  color: $color-greytext;
  font-family: $font-secondary;
  font-size: $s;
  padding: 20px 0;
  margin-bottom: 5px;
}

.tag_container {
  margin: 5px 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;
  }
}

.c-tabs {
  margin-bottom: 40px;

  .b-tabs {
    font-weight: $bold;
    color: $color-navy;
    font-size: $m;
  }

  h2 {
    font-weight: 700;
    color: $color-navy;
    font-size: $l;
    margin: 20px auto;
  }

  p {
    margin-top: 8px;
    font-family: Noto Sans, sans-serif;
    font-size: $s;
    color: $color-greytext;
  }
}

.pagination {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
</style>
