<template>
  <BContainer class="container">
    <BModal 
        id="modal-center" 
        v-model="activeModal" 
        centered 
        title="consumo-cuidado" 
        :ok-variant="modalColor"> {{ modalText }}
    </BModal>
    <BRow align-h="center">
      <BCol class="edit-product">
        <h1 class="title">Editar producto</h1>
        <ProductForm :product-form="form" @send="submitProduct" />
        <div v-if="form.source !== 'MANUAL'" class="data">
          <dl class="creation-data">
            <dt>Fecha de creación:</dt>
            <dd>{{ formatDatetime(form.created) }}</dd>

            <dt>Fecha de actualización:</dt>
            <dd>{{ formatDatetime(form.updated) }}</dd>
          </dl>
          <dl class="import-data">
            <dt>Fecha de importación:</dt>
            <dd>{{ formatDatetime(form.sync_date) }}</dd>

            <dt>Importado desde:</dt>
            <dd>{{ form.source }}</dd>
          </dl>
        </div>
      </BCol>
    </BRow>
  </BContainer>
</template>

<script>
import dataProcessing from '~/utils/dataProcessing'
import { useAuthStore } from '@/stores/auth'
export default {
  setup() {
    definePageMeta({
      layout: 'editar',
      middleware: 'auth',
      auth: { authority: 'COOP_MANAGER' },
    })
    const auth = useAuthStore();
    return {
      auth
    }
  },

  data() {
    return {
      form: {},
      activeModal: false,
      modalText: '',
      modalColor: '',
    }
  },

  async created() {
    try {
      const config = useRuntimeConfig()
      const route = useRoute()
      this.form = await $fetch(`my_products/${route.params.id}/`, {
        baseURL: config.public.baseURL,
        method: 'GET',
        headers: {
          Authorization: `Bearer ${this.auth.access}`,
        },
      })
      if (this.form.source !== 'MANUAL' && this.form.history) {
        try {
          //TODO: Review Fetching the sync date from the history endpoint
          const result = await $fetch(`history/${this.form.history}/`, {
            baseURL: config.public.baseURL,
            method: 'GET',
            headers: {
              Authorization: `Bearer ${this.auth.access}`,
            },
          })
          form.sync_date = result.data.sync_date
        } catch (error) {
          console.error(error)
          form.sync_date = null
        }
      }
    } catch (error) {
      console.error(error)
    }
  },

  methods: {
    formatDatetime: dataProcessing.formatDatetime,

    async submitProduct(value) {
      console.log('Submitting product:', value)
      const config = useRuntimeConfig()
      const route = useRoute()
      //TODO: review PUT method, its sending 200 status but not updating the product
      try {
        await $fetch(`/my_products/${route.params.id}/`, {
          baseURL: config.public.baseURL,
          method: 'PUT',
          body: value,
          headers: {
            Authorization: `Bearer ${this.auth.access}`,
          },
        })
        this.modalText = 'Producto actualizado correctamente'
        this.modalColor = 'success'
        this.activeModal = true
      } catch (error) {
        this.modalText = 'Ha habido un error'
        this.modalColor = 'danger'
        this.activeModal = true
        console.error('Error updating product:', error)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 40px;
  margin-bottom: 80px;
}
.edit-product {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  width: 60%;
  font-size: $h2;
  color: $color-primary;
  margin-bottom: 10px;
  text-align: left;
}
.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-between;
  color: $color-greytext;
}
.creation-data,
.import-data {
  padding: 20px;
}
</style>
