<template>
  <BContainer class="container">
    <BRow>
      <BCol>
        <h1 class="title">
          Productos
          <button
            class="ml-4 mb-1 btn btn-outline-primary btn-sm"
            @click="redirectToNewProduct"
          >
            +
          </button>
        </h1>
      </BCol>
    </BRow>
    <BRow>
      <BCol class="d-flex flex-row-reverse">
        <button class="btn btn-secondary" :disabled="selectedItemsIndexes.length === 0" @click="desactivateProducts">
          Desactivar
        </button>
        <button class="btn btn-primary mr-3" :disabled="selectedItemsIndexes.length === 0" @click="activateProducts">
          Activar
        </button>
        <div v-show="selectedItemsIndexes.length !== 0" class="selected-products mr-3">
          {{ selectedItemsIndexes.length }} productos seleccionados
        </div>
      </BCol>
    </BRow>
    <BRow>
      <template v-if="products">
        <v-data-table
          v-model="selectedItemsIndexes"
          show-select
          :single-select="singleSelect"
          :headers="headers"
          :items="products"
          :search="search"
          :loading="loading"
          loading-text="Cargando productos..."
        >
          <template #top>
            <v-toolbar flat color="white">
              <!-- Search -->
              <v-text-field
                v-model="search"
                append-icon="mdi-magnify"
                label="Buscar producto"
                single-line
                hide-details
              />
              <!-- . Search -->
            </v-toolbar>
          </template>
          <template #[`item.active`]="item">
            <v-icon v-if="item.item.active" small class="mr-2">
              mdi-check
            </v-icon>
            <v-icon v-else small class="mr-2"> mdi-close </v-icon>
          </template>
          <template #[`item.actions`]="item">
            <NuxtLink :to="`/editar/productos/${item.item.id}`">
              <v-icon small class="mr-2"> mdi-pencil </v-icon>
            </NuxtLink>
            <v-icon small class="mr-2" @click="deleteItem(item)">
              mdi-delete
            </v-icon>
          </template>
        </v-data-table>
      </template>
    </BRow>
    <BModal 
        id="modal-center" 
        v-model="activeModal" 
        centered 
        title="latienda.coop" 
        :ok-variant="modalColor"> {{ modalText }}
      </BModal>
  </BContainer>
</template>

<script>
export default {
  setup() {
    definePageMeta({
      layout: 'editar',
      middleware: 'auth',
      auth: { authority: 'COOP_MANAGER' },
    })
    const auth = useAuthStore();
    return {
      auth
    }
  },

  data() {
    return {
      products: [],
      totalProducts: 0,
      loading: true,
      singleSelect: false,
      selectedItemsIndexes: [],
      search: '',
      options: {},
      headers: [
        { title: 'ID', value: 'id' },
        { title: 'Nombre', value: 'name' },
        { title: 'Categoría', value: 'category' },
        { title: 'Activo', value: 'active' },
        { title: 'Precio', value: 'price' },
        { title: 'Fuente', value: 'source' },
        { title: 'Stock', value: 'stock' },
        { title: 'Acción', value: 'actions' },
      ],
      activeModal: false,
      modalText: '',
      modalColor: '',
    }
  },

  computed: {
    selectedItems() {
      const itemsArr = []
      this.selectedItemsIndexes.forEach(index => {
        this.products.forEach(item => {
          if (item.id === index) {
            itemsArr.push(item)
          }
        })
      })
      return itemsArr
    }
  },

  async created() {
    if (this.$route.params.action === 'created') {
      this.$bvToast.toast(`Producto creado`, {
        title: 'latienda.coop',
        autoHideDelay: 5000,
        appendToast: true,
        variant: 'success',
      })
    }
    await this.getDataFromApi()
  },

  methods: {
    async getDataFromApi() {
      this.loading = true
      const config = useRuntimeConfig()
      const data = await $fetch(`/my_products/`, {
        baseURL: config.public.baseURL,
        method: 'GET',
        headers: {
          Authorization: `Bearer ${this.auth.access}`,
        },
      })
      this.products = data
      this.loading = false
    },

    async deleteItem(item) {
      if (confirm('Confirma que quieres eliminar este producto')) {
        const config = useRuntimeConfig()
        try {
          await $fetch(`/my_products/${item.item.id}`, {
            baseURL: config.public.baseURL,
            method: 'DELETE',
            headers: {
              Authorization: `Bearer ${this.auth.access}`,
            },
          })
          const index = this.products.indexOf(item.item)
          this.products.splice(index, 1)
          this.selectedItemsIndexes = []
          this.modalText = 'Los productos han sido eliminados correctamente.'
          this.modalColor = 'success'
          this.activeModal = true
        } catch (error) {
          console.error(error)
          this.modalText = 'Ha habido un error'
          this.modalColor = 'danger'
          this.activeModal = true
        }
      }
    },

    async activateProducts() {
      try {
        const config = useRuntimeConfig()
        await this.selectedItems.forEach(async (item) => {
          await $fetch(`/my_products/${item.id}/`, {
            baseURL: config.public.baseURL,
            method: 'PATCH',
            body: {
              active: true
            },
            headers: {
              Authorization: `Bearer ${this.auth.access}`
            }
          })
          const index = this.products.indexOf(item)
          this.products[index].active = true
        })
        this.selectedItemsIndexes = []
        this.modalText = 'Los productos han sido activados correctamente.'
        this.modalColor = 'success'
        this.activeModal = true
      } catch (error) {
        console.error(error)
        this.modalText = 'Ha habido un error'
        this.modalColor = 'danger'
        this.activeModal = true
      }
    },
    async desactivateProducts() {
      try {
        const config = useRuntimeConfig()
        await this.selectedItems.forEach(async (item) => {
          await $fetch(`/my_products/${item.id}/`, {
            baseURL: config.public.baseURL,
            method: 'PATCH',
            body: {
              active: false
            },
            headers: {
              Authorization: `Bearer ${this.auth.access}`
            }
          })
          const index = this.products.indexOf(item)
          this.products[index].active = false
        })
        this.selectedItemsIndexes = []
        this.modalText = 'Los productos han sido desactivados correctamente.'
        this.modalColor = 'success'
        this.activeModal = true
      } catch (error) {
        console.error(error)
        this.modalText = 'Ha habido un error'
        this.modalColor = 'danger'
        this.activeModal = true
      }
    },

    redirectToNewProduct() {
      this.$router.push({
        name: 'editar-productos-crear',
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.container {
  margin-top: 40px;
  margin-bottom: 80px;
}
.title {
  color: $color-navy;
  font-size: $xxl;
  margin-bottom: 60px;
  @include mobile {
    margin-top: 70px;
  }
}
v-toolbar {
  padding: 0;
}
.selected-products {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-items: center;
}
</style>
