<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="cargando">
                    {{ 'Cargando ' + archivo.nombre }}
                </span>
            </label>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import { mapActions } from "vuex";

export default {
    name: "CanastaInput",
    data() {
        return {
            archivo: null,
            cargando: false,
        };
    },
    methods: {
        ...mapActions('ui',["toast"]),
        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.toast({ mensaje: (response.data.message || "Canasta cargada exitosamente") });
                } catch (error) {
                    this.toast({ mensaje: (error.response?.data?.message || "Hubo errores.") });
                } finally {
                    this.cargando = false;
                    this.archivo = null;
                }
            } else {
                this.toast("La canasta debe ser .CSV")
                this.archivo = null;
            }
        },
    },
};
</script>

<style scoped>

</style>