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

/** Definidores */
const router = useRouter();
const route = useRoute();

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

const parentInfo = ref(null);

/** Métodos */
function submit() {
    form.transform(data => ({
        ...data,
        parent_id: data.parent_id // Usar el parent_id del formulario
    })).post(apiTo('store'), {
        onSuccess: () => {
            Notify.success(Lang('register.create.onSuccess'))
            router.push(viewTo({ name: 'index' }));
        }
    })
}

/** Ciclos */
onMounted(() => {
    // Verificar si se están pasando parámetros para crear subcategoría
    if (route.query.parent_id) {
        parentInfo.value = {
            id: parseInt(route.query.parent_id),
            name: route.query.parent_name,
            code: route.query.parent_code
        };
        // Pre-llenar el parent_id en el formulario
        form.parent_id = parseInt(route.query.parent_id);
    }
})
</script>

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