<template>
  <BContainer class="container">
    <BModal 
        id="modal-center" 
        v-model="activeModal" 
        centered 
        title="latienda.coop" 
        ok-variant="danger"> {{ modalText }}
    </BModal>
    <BRow align-h="center">
      <BCol class="add-product">
        <h1 class="title">Añadir producto</h1>
        <ProductForm @send="submitProduct" />
      </BCol>
    </BRow>
  </BContainer>
</template>

<script>
import { useAuthStore } from '@/stores/auth'
export default {
  setup() {
    definePageMeta({
      layout: 'editar',
      middleware: 'auth',
      auth: { authority: 'COOP_MANAGER' },
    })
    const auth = useAuthStore();
    return {
      auth
    }
  },
  data() {
    return {
      activeModal: false,
      modalText: '',
    }
  },
  methods: {
    async submitProduct(value) {
      console.log('Creating product:', value)
      const config = useRuntimeConfig()
      try {
        await $fetch(`/products/`, {
          baseURL: config.public.baseURL,
          method: 'POST',
          body: value,
          headers: {
            Authorization: `Bearer ${this.auth.access}`,
          },
        })
        this.$router.push({
          name: 'editar-productos',
          params: { action: 'created' },
        })
      } catch (error) {
        this.modalText = 'Ha habido un error'
        this.activeModal = true
        console.error('Error updating product:', error)
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 40px;
  margin-bottom: 80px;
}
.add-product {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  color: $color-navy;
  font-size: $xxl;
  margin-bottom: 60px;
  text-align: left;
  @include desktop {
    width: 40%;
  }
  @include tablet {
    width: 60%;
  }
  @include mobile {
    width: 90%;
    margin-top: 70px;
  }
}
.help-text {
  border: 1px solid $color-greylayout;
  border-radius: 8px;
  padding: 12px;
  text-align: justify;
  hyphens: auto;
  font-size: $xs;
  font-weight: $regular;
  color: $color-greylayout;
  font-family: $font-secondary;
  background-color: $color-light;

  a {
    text-decoration: underline;
    color: $color-greytext;
  }
}

.data {
  margin: 0 100px;
  margin-top: 80px;
  font-size: $xs;
  display: flex;
  justify-content: space-evenly;
  color: $color-greytext;
}
</style>
