<script setup>
import { ref, onMounted } from 'vue';
import { transl } from './Module';
import UnitsMeasureService from './services/UnitsMeasureService';

import PrimaryButton from '@Holos/Button/Primary.vue';
import Input         from '@Holos/Form/Input.vue';
import Selectable    from '@Holos/Form/Selectable.vue';
import Checkbox      from '@Holos/Checkbox.vue';

/** Eventos */
const emit = defineEmits([
    'submit'
])

/** Servicios */
const unitsService = new UnitsMeasureService();

/** Propiedades reactivas */
const typeOptions = ref([]);
const loadingTypes = ref(true);

/** Propiedades */
defineProps({
    action: {
        default: 'create',
        type: String
    },
    form: Object
})

/** Métodos */
function submit() {
    emit('submit')
}

/** Cargar tipos de medida desde la API */
async function loadUnitTypes() {
    try {
        loadingTypes.value = true;
        typeOptions.value = await unitsService.getUnitTypes();
    } catch (error) {
        console.error('Error cargando tipos de medida:', error);
        // Usar tipos por defecto en caso de error
        const fallbackTypes = unitsService.getTypes().map(type => ({
            value: type.id,
            label: type.name
        }));
        typeOptions.value = fallbackTypes;
    } finally {
        loadingTypes.value = false;
    }
}

/** Ciclo de vida */
onMounted(() => {
    loadUnitTypes();
});
</script>

<template>
    <div class="w-full pb-2">
        <p class="text-justify text-sm" v-text="transl(`form.${action}.description`)" />
    </div>
    <div class="w-full">
        <form @submit.prevent="submit" class="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            <Input
                v-model="form.code"
                id="code"
                :onError="form.errors.code"
                autofocus
                required
            />
            <Input
                v-model="form.name"
                id="name"
                :onError="form.errors.name"
                required
            />
            <Input
                v-model="form.abbreviation"
                id="Abreviación"
                :onError="form.errors.abbreviation"
                required
            />

            <Selectable
                v-model="form.type"
                id="type"
                title="Tipo de medida"
                label="label"
                :onError="form.errors.type"
                :options="typeOptions"
                :disabled="loadingTypes"
                required
            />
           
            <div class="md:col-span-2 lg:col-span-3 xl:col-span-4">
                <PrimaryButton
                    :loading="form.processing"
                    :disabled="form.processing"
                >
                    Crear unidad de medida
                </PrimaryButton>
            </div>
        </form>
    </div>
</template>