<template>
  <div class="container">
    <BModal 
        id="modal-center" 
        v-model="activeModal" 
        centered 
        title="consumo-cuidado" 
        :ok-variant="modalColor"> {{ modalText }}
    </BModal>
    <div class="row">
      <div class="col-10"></div>
      <h1 class="title">Importar productos desde CSV</h1>
    </div>
    <form @submit.prevent="submitFile">
      <div class="cont-col">
        <label for="file"> Archivo .csv</label>
        <input
          id="file"
          type="file"
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          placeholder="Elige un archivo"
          required
          @change="handleFile"
        />
      </div>
      <p v-if="error" class="error">{{ error }}</p>
      <SubmitButton text="Importar" />
    </form>
  </div>
</template>

<script>
import { useAuthStore } from '@/stores/auth'
export default {
  setup() {
    definePageMeta({
      layout: 'admin',
      middleware: 'auth',
      auth: { authority: 'SITE_ADMIN' },
    })
    const auth = useAuthStore();
    return {
      auth
    }
  },
  data() {
    return {
      file: null,
      error: null,
      modalText: '',
      modalColor: '',
      activeModal: false
    }
  },

  methods: {
    async handleFile(e) {
      const selectedFile = await e.target.files[0]
      this.file = selectedFile
    },

    async submitFile() {
      this.error = null
      const formData = new FormData()
      formData.append('csv_file', this.file)
      //TODO: Review functionality
      try {
        await $fetch('/load_coops/',{
          baseURL: config.public.baseURL,
          method: 'POST',
          body: formData,
          headers: {
            Authorization: `Bearer ${this.auth.access}`,
          },
        })
        this.modalText = 'Productos importados correctamente'
        this.modalColor = 'success'
        this.activeModal = true
      } catch (error) {
        this.error = 'Ha habido un error'
        console.error('Error importing products:', error)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  // margin-top: 40px;
  margin-bottom: 80px;
}
.title {
  color: $color-navy;
  font-size: $xxl;
  margin-bottom: 2.5rem;
}
.cont-col {
  margin: 15px 0;
  display: flex;
  flex-direction: column;
}

label {
  text-align: left;
  color: $color-navy;
  font-weight: $bold;
  font-size: $xs;
}

.error {
  color: $color-error;
}
</style>
