<template>
    <div class="block">
        <div class="file has-name is-right">
            <label class="file-label">
                <input
                    class="file-input"
                    type="file"
                    name="canasta"
                    @change="archivoSubido"
                />
                <span class="file-cta">
                    <span class="file-icon">
                      <i class="fas fa-cloud-upload-alt"></i>
                    </span>
                    <span class="file-label">Subir canasta</span>
                </span>
                <span class="file-name" v-if="archivo">
                    {{ 'Cargando ' + archivo.nombre }}
                </span>
            </label>
        </div>
    </div>
</template>

<script>
import axios from "axios";

export default {
    name: "CanastaInput",
    data() {
        return {
            archivo: null,
            cargando: false,
        };
    },
    methods: {
        async archivoSubido(event) {
            const archivo = event.target.files[0];
            if (archivo && archivo.type === "text/csv") {
                this.archivo = {data: archivo, nombre: archivo.name};
                const formData = new FormData();
                formData.append("data", this.archivo.data);

                try {
                    this.cargando = true;
                    const response = await axios.post("/compras/canasta", formData, {
                        headers: {
                            "Content-Type": "multipart/form-data",
                        },
                    });
                    this.$root.$toast(response.data.message || "Canasta cargada exitosamente");
                } catch (error) {
                    this.$root.$toast(error.response?.data?.message || "Hubo errores.");
                } finally {
                    this.cargando = false;
                    this.archivo = null;
                }
            } else {
                this.$root.$toast("La canasta debe ser .CSV")
                this.archivo = null;
            }
        },
    },
};
</script>

<style scoped>

</style>