<script setup>
import { onMounted, ref } from 'vue';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import { api, useForm } from '@Services/Api';
import { viewTo, apiTo, transl } from './Module';

import IconButton      from '@Holos/Button/Icon.vue'
import PageHeader      from '@Holos/PageHeader.vue';
import GoogleIcon      from '@Shared/GoogleIcon.vue';
import Form            from './Form.vue'

/** Definiciones */
const vroute = useRoute();
const router = useRouter();

/** Propiedades */
const form = useForm({
    id: null,
    code: '',
    name: '',
    description: '',
});

const parentOptions = ref([]);

/** Métodos */
function submit() {
    form.transform(data => ({
        ...data,
    })).put(apiTo('update', { comercial_classification: form.id }), {
        onSuccess: () => {
            Notify.success(Lang('register.edit.onSuccess'))
            router.push(viewTo({ name: 'index' }));
        },
    })
}

/** Función para obtener clasificaciones padre (excluyendo la actual y sus hijos) */
function loadParentOptions() {
    api.get(apiTo('index'), {
        onSuccess: (r) => {
            // Función para excluir la clasificación actual y sus descendientes
            const excludeCurrentAndChildren = (items, excludeId) => {
                return items.filter(item => {
                    if (item.id === excludeId) return false;
                    if (hasDescendant(item, excludeId)) return false;
                    return true;
                }).map(item => ({
                    ...item,
                    children: excludeCurrentAndChildren(item.children || [], excludeId)
                }));
            };

            // Función para verificar si un item tiene como descendiente la clasificación actual
            const hasDescendant = (item, targetId) => {
                if (!item.children) return false;
                return item.children.some(child => 
                    child.id === targetId || hasDescendant(child, targetId)
                );
            };

            // Aplanar la estructura jerárquica para el selector
            const flattenOptions = (items, level = 0) => {
                let options = [];
                items.forEach(item => {
                    options.push({
                        ...item,
                        name: '  '.repeat(level) + item.name, // Indentación visual
                        level
                    });
                    if (item.children && item.children.length > 0) {
                        options = options.concat(flattenOptions(item.children, level + 1));
                    }
                });
                return options;
            };

            const dataSource = r.data?.comercial_classifications?.data || r.comercial_classifications || [];
            const filteredData = excludeCurrentAndChildren(dataSource, form.id);
            parentOptions.value = flattenOptions(filteredData);
        }
    });
}

onMounted(() => {
    api.get(apiTo('show', { comercial_classification: vroute.params.id }), {
        onSuccess: (r) => {
            const classification = r.data || r.comercial_classification || r;
            form.fill({
                id: classification.id,
                code: classification.code,
                name: classification.name,
                description: classification.description,
                is_active: classification.is_active,
                parent: classification.parent || null
            });
            
            // Cargar opciones padre después de obtener los datos actuales
            loadParentOptions();
        }
    });
})
</script>

<template>
    <PageHeader :title="`${transl('edit.title')}${form.parent ? ' - Subcategoría' : ''}`">
        <RouterLink :to="viewTo({ name: 'index' })">
            <IconButton
                class="text-white"
                icon="arrow_back"
                :title="$t('return')"
                filled
            />
        </RouterLink>
    </PageHeader>
    
    <!-- Mostrar información del padre si es una subcategoría -->
    <div v-if="form.parent" class="mb-4 p-4 bg-yellow-50 dark:bg-yellow-900 rounded-lg border border-yellow-200 dark:border-yellow-700">
        <div class="flex items-center">
            <GoogleIcon class="text-yellow-600 text-xl mr-2" name="account_tree" />
            <div>
                <p class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
                    Editando subcategoría de:
                </p>
                <p class="text-lg font-semibold text-yellow-900 dark:text-yellow-100">
                    <code class="bg-yellow-100 dark:bg-yellow-800 px-2 py-1 rounded text-sm mr-2">{{ form.parent.code }}</code>
                    {{ form.parent.name }}
                </p>
            </div>
        </div>
    </div>
    
    <Form
        action="update"
        :form="form"
        :parent-options="parentOptions"
        @submit="submit"
    />
</template>