<script setup>
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useSearcher, apiURL } from '@Services/Api';

import Table from '@Holos/Table.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import CreateModal from './CreateBulkModal.vue';
import EditModal from './EditModal.vue';
import DeleteModal from './DeleteModal.vue';

const route = useRoute();
const router = useRouter();

const categoryId = route.params.id;

/** Estado */
const models = ref([]);
const categoryName = ref('');
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingSubcategory = ref(null);
const deletingSubcategory = ref(null);

/** Cargar nombre de la categoría padre */
const loadCategory = async () => {
    try {
        const response = await fetch(apiURL(`categorias/${categoryId}`), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        if (result.data?.model) {
            categoryName.value = result.data.model.name;
        }
    } catch (error) {
        console.error('Error loading category:', error);
    }
};

/** Métodos */
const searcher = useSearcher({
    url: apiURL(`categorias/${categoryId}/subcategorias`),
    onSuccess: (r) => {
        models.value = r.subcategories || { data: [], total: 0 };
    },
    onError: () => models.value = { data: [], total: 0 }
});

const openCreateModal = () => {
    showCreateModal.value = true;
};

const closeCreateModal = () => {
    showCreateModal.value = false;
};

const openEditModal = (subcategory) => {
    editingSubcategory.value = subcategory;
    showEditModal.value = true;
};

const closeEditModal = () => {
    showEditModal.value = false;
    editingSubcategory.value = null;
};

const openDeleteModal = (subcategory) => {
    deletingSubcategory.value = subcategory;
    showDeleteModal.value = true;
};

const closeDeleteModal = () => {
    showDeleteModal.value = false;
    deletingSubcategory.value = null;
};

const onSubcategorySaved = () => {
    searcher.search();
};

const confirmDelete = async (id) => {
    try {
        const response = await fetch(apiURL(`categorias/${categoryId}/subcategorias/${id}`), {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });

        if (response.ok) {
            Notify.success('Subclasificación eliminada exitosamente');
            closeDeleteModal();
            searcher.search();
        } else {
            Notify.error('Error al eliminar la subclasificación');
        }
    } catch (error) {
        console.error('Error:', error);
        Notify.error('Error al eliminar la subclasificación');
    }
};

/** Ciclos */
onMounted(() => {
    loadCategory();
    searcher.search();
});
</script>

<template>
    <div>
        <!-- Header -->
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
                <button
                    @click="router.push({ name: 'pos.category.index' })"
                    class="flex items-center justify-center w-8 h-8 rounded-lg text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-gray-200 dark:hover:bg-gray-800 transition-colors"
                    title="Volver a clasificaciones"
                >
                    <GoogleIcon name="arrow_back" class="text-xl" />
                </button>
                <div>
                    <p class="text-xs text-gray-500 dark:text-gray-400">Clasificación</p>
                    <h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">
                        {{ categoryName || 'Subclasificaciones' }}
                    </h1>
                </div>
            </div>
            <button
                class="flex items-center gap-2 px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                @click="openCreateModal"
            >
                <GoogleIcon name="add" class="text-xl" />
                Nueva Subclasificación
            </button>
        </div>

        <!-- Modales -->
        <CreateModal
            :show="showCreateModal"
            :category-id="categoryId"
            @close="closeCreateModal"
            @created="onSubcategorySaved"
        />

        <EditModal
            :show="showEditModal"
            :category-id="categoryId"
            :subcategory="editingSubcategory"
            @close="closeEditModal"
            @updated="onSubcategorySaved"
        />

        <DeleteModal
            :show="showDeleteModal"
            :subcategory="deletingSubcategory"
            @close="closeDeleteModal"
            @confirm="confirmDelete"
        />

        <!-- Tabla -->
        <div class="pt-2 w-full">
            <Table
                :items="models"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page)"
            >
                <template #head>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">NOMBRE</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">DESCRIPCIÓN</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ESTADO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ACCIONES</th>
                </template>
                <template #body="{items}">
                    <tr
                        v-for="model in items"
                        :key="model.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ model.name }}</p>
                        </td>
                        <td class="px-6 py-4">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ model.description || '-' }}</p>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span
                                class="inline-flex px-3 py-1 text-xs font-semibold rounded-full"
                                :class="{
                                    'bg-green-50 text-green-700': model.is_active,
                                    'bg-red-50 text-red-700': !model.is_active
                                }"
                            >
                                {{ model.is_active ? 'Activo' : 'Inactivo' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    @click="openEditModal(model)"
                                    class="text-indigo-600 hover:text-indigo-900 transition-colors"
                                    title="Editar subclasificación"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    @click="openDeleteModal(model)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar subclasificación"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="4" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                name="category"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">No hay subclasificaciones registradas</p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
    </div>
</template>
