<template>
  <div class="content">
    <div class="c-description">
      <div class="c-image-links">
        <div class="c-image-container">
          <img v-if="coop?.logo" :src="coop?.logo" alt="" />
          <img v-else src="@/assets/img/consumo-default.png" alt="" />
        </div>
        <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>COMPRA EN SU TIENDA</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>CONOCE MÁS SU PROYECTO</span>
        </BButton>
      </div>
      <div class="c-text">
        <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"
          >
            <span>{{ n }}</span>
          </NuxtLink>
        </div>
        <div class="coop-links">
          <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?.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 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>
    <div class="c-tabs-container">
      <div class="c-tabs">
        <div>
          <BCard no-body class="b-card">
            <BTabs v-model:index="tabIndex"  class="b-tabs">
              <BTab
                active
                :title-link-class="tabIndex === 0 ? ['#F28C8C', '#FFFF'] : ['#FAD1D1', '#000']"
                :class="{
                  'b-tab-active': tabIndex === 0,
                }"
              >
                <template #title>
                  <img class="div-action-img" src="@/assets/img/truck.svg" />
                  Envío
                </template>
                <BCardText>
                  {{
                    coop?.shipping_terms ||
                    'Consultar con la cooperativa para más información'
                  }}
                </BCardText>
              </BTab>
              <BTab
                :class="{
                  'b-tab-active': tabIndex === 1,
                }"
              >
                <template #title>
                  <img class="div-action-img" src="@/assets/img/info.svg" />
                  Devoluciones, garantías y reembolsos
                </template>
                <BCardText>
                  {{
                    coop?.sale_terms ||
                    'Consultar con la cooperativa para más información'
                  }}
                </BCardText>
              </BTab>
            </BTabs>
          </BCard>
        </div>
      </div>
    </div>
    <div v-if="products && products.length" class="c-catalogo">
      <div class="title-container">
        <div class="title-lines"></div>
        <h5 class="items-title">Nuestro catálogo</h5>
        <div class="title-lines"></div>
      </div>
      <div class="cards-grid">
        <div v-for="product in slicedProducts" :key="product.id">
          <ProductCard :key="product.key" :product="product" />
        </div>
        </div>
        <div class="c-pagination">
          <BPagination 
            v-model="currentPage"
            :v-if="products"
            :total-rows="rows"
            :per-page="perPage"
          />
        </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'pinia'
export default {
  setup(){
    definePageMeta({
      layout: 'default',
    })
  },
  //TODO: implement head() method
  // head() {
  //   return {
  //     title: `consumo-cuidado | ${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: 8,
      tabIndex: 0,
    }
  },
  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',
          headers: {
            Authorization: '/',
          },
        }
      )
     this.products = await $fetch(
        `/products?company=${$route.params.id}`,
        {
          baseURL: config.public.baseURL,
          method: 'GET',
          headers: {
            Authorization: '/',
          },
        }
      )
    } 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>
.content {
  // margin-top: 80px;
  // margin-bottom: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2rem;
}

.c-description {
  display: flex;
  flex-direction: row;
  align-items: start;
  justify-content: start;
  gap: 4rem;
  width: 100%;
  padding: 4rem 4rem;
  border-radius: var(--rounded-3xl, 24px);
  background: linear-gradient(
      180deg,
      $color-consumo-base-extra-light 0%,
      $color-bg-light 100%
    );

  @media screen and (max-width: 1024px) {
    flex-direction: column;
    gap: 2rem;
    margin-top: 4rem;
    padding: 3rem 2rem;
  }
  @include mobile {
    flex-direction: column;
    gap: 1rem;
    margin-top: 5rem;
    padding: 2rem 1rem;
  }
  .c-image-links {
    display: flex;
    flex-direction: column;
    width: auto;
    gap: 1.5rem;
    @include mobile {
      flex-direction: column;
      margin-right: 0;
    }

    .div-link:hover {
      background-color: white;
      transition: all 0.2s ease;
    }

    .div-link {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 0.7rem;
      width: 100%;
      border: 1px solid $color-button;
      border-radius: 5px;
      background-color: transparent;
      font-weight: $bold;
      padding: 15px 0;

      .div-link-img {
        width: 20px;
      }
      span {
        color: $color-button;
      }
    }
  }
}

.coop-links {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;

  .div-action {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: start;
    padding-left: 8px;
    background-color: transparent;
    font-size: $m;
  }

  .div-action-img {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    margin-left: 5px;
  }
}

.c-image-container {
  height: 300px;
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  align-items: center;
  justify-content: center;
  background-color: white;
  border-radius: 16px;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  @include mobile {
    width: 200px;
    height: 200px;
    margin: 0 auto;
  }
}

.c-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  @include mobile {
    margin-top: 2rem;
  }

  .coop-name {
    font-size: $h2;
    font-weight: $bold;
    text-transform: capitalize;
  }
  .coop-text {
    margin-top: 8px;
    font-size: $m;
    width: 80%;
    @include tablet {
      width: 100%;
    }
    @include mobile {
      width: 100%;
  }
}
}

.tags_container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: start;
  gap: 8px;

  .tag_container {
    margin: 5px 6px 0 0;
    border-radius: 1rem;
    padding: 8px;
    display: inline-block;
    font-family: $font-secondary;
    font-size: $xs;
    background-color: white;
    color: #4B4B4B;
    text-align: center;
    text-transform: uppercase;
    text-decoration: none;
  }
}

.c-tabs-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 100%;

  .c-tabs {
    margin-bottom: 40px;
    width: 100%;
    .b-card {
      border: none;
      box-shadow: none;
      background-color: transparent;
    }
    .b-tabs {
      font-weight: $bold;
      background-color: $color-consumo-base-light;
      border-radius: 24px;
      font-size: $m;
    }
    .b-tab {
      color: white;
      &:hover {
        color: $color-consumo-base-light;
      }
    }
    .b-tab-active {
      background-color: $color-consumo-base-extra-light;
      border-radius: 0 0 24px 24px;
      background: linear-gradient(
            180deg,
            $color-consumo-base-extra-light 0%,
            $color-bg-light 100%
          );
    }

    h2 {
      font-size: $h5;
      margin: 20px auto;
      text-transform: uppercase;

      &:hover {
        color: $color-bg-light;
      }
    }

    p {
      padding: 3rem 4rem;
      font-size: $m;
    }
  }
}

.c-catalogo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 24px;
  padding: 4rem 4rem;
  background: $color-bg-light;
  width: 100%;
  &-title {
    text-align: center;
  }
  .title-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 1rem;
    .title-lines {
      width: 34px;
      height: 2px;
      background: $color-consumo-base;
      margin: 0 8px;
    }
    .items-title {
      font-size: $h5;
      text-transform: uppercase;
      padding-top: 10px;
    }
  }
  .cards-grid {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    align-content: flex-start;
    gap: 32px var(--spacing-p-8, 32px);
    align-self: stretch;
    flex-wrap: wrap;
    margin-top: 2rem;
  }
  .c-pagination {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 100%;
    margin-top: 4rem;
  }
}


</style>
