<script setup>
import { ref } from 'vue';
import { useForm, apiURL } from '@Services/Api';

import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import FormError from '@Holos/Form/Elements/Error.vue';

/** Eventos */
const emit = defineEmits(['close', 'created']);

/** Propiedades */
const props = defineProps({
    show: Boolean,
    categoryId: {
        type: [String, Number],
        required: true
    }
});

/** Estado: lista de subcategorías a crear */
const emptyEntry = () => ({ name: '', description: '', is_active: true });
const entries = ref([emptyEntry()]);

const addEntry = () => entries.value.push(emptyEntry());

const removeEntry = (index) => {
    if (entries.value.length > 1) {
        entries.value.splice(index, 1);
    }
};

/** Formulario */
const form = useForm({});

/** Métodos */
const createSubcategory = () => {
    const payload = entries.value.length === 1
        ? entries.value[0]
        : entries.value;

    form.transform(() => payload).post(apiURL(`categorias/${props.categoryId}/subcategorias`), {
        onSuccess: (data) => {
            Notify.success(
                entries.value.length === 1
                    ? 'Subclasificación creada exitosamente'
                    : 'Subclasificaciones creadas exitosamente'
            );
            emit('created', data?.models ?? data?.model);
            closeModal();
        },
        onError: () => {
            Notify.error('Error al crear la subclasificación');
        }
    });
};

const closeModal = () => {
    entries.value = [emptyEntry()];
    form.reset();
    emit('close');
};
</script>

<template>
    <Modal :show="show" max-width="md" @close="closeModal">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                    Crear Subclasificación
                </h3>
                <button
                    @click="closeModal"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="createSubcategory" class="space-y-4">

                <!-- Entradas dinámicas -->
                <div
                    v-for="(entry, index) in entries"
                    :key="index"
                    class="space-y-3"
                    :class="{ 'border-t border-gray-200 dark:border-gray-700 pt-4': index > 0 }"
                >
                    <div v-if="entries.length > 1" class="flex items-center justify-between">
                        <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Subclasificación {{ index + 1 }}
                        </span>
                        <button
                            type="button"
                            @click="removeEntry(index)"
                            class="text-red-400 hover:text-red-600 transition-colors"
                            title="Eliminar entrada"
                        >
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>

                    <!-- Nombre -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOMBRE
                        </label>
                        <FormInput
                            v-model="entry.name"
                            type="text"
                            placeholder="Nombre de la subclasificación"
                            required
                        />
                        <FormError :message="form.errors?.[`${index}.name`] ?? form.errors?.name" />
                    </div>

                    <!-- Descripción -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            DESCRIPCIÓN
                        </label>
                        <textarea
                            v-model="entry.description"
                            rows="2"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100"
                            placeholder="Descripción de la subclasificación"
                        ></textarea>
                        <FormError :message="form.errors?.[`${index}.description`] ?? form.errors?.description" />
                    </div>

                    <!-- Estado -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            ESTADO
                        </label>
                        <select
                            v-model="entry.is_active"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100"
                        >
                            <option :value="true">Activo</option>
                            <option :value="false">Inactivo</option>
                        </select>
                        <FormError :message="form.errors?.[`${index}.is_active`] ?? form.errors?.is_active" />
                    </div>
                </div>

                <!-- Agregar otra -->
                <button
                    type="button"
                    @click="addEntry"
                    class="flex items-center gap-1.5 text-sm font-medium text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Agregar otra subclasificación
                </button>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6">
                    <button
                        type="button"
                        @click="closeModal"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="px-4 py-2 text-sm font-semibold text-white bg-gray-900 rounded-lg hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                        <span v-if="form.processing">Guardando...</span>
                        <span v-else>Guardar</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>
</template>
