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

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

const router = useRouter();

/** Estado */
const models = ref([]);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingCategory = ref(null);
const deletingCategory = ref(null);

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

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

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

const openEditModal = (category) => {
    editingCategory.value = category;
    showEditModal.value = true;
};

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

const openDeleteModal = (category) => {
    deletingCategory.value = category;
    showDeleteModal.value = true;
};

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

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

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

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

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

<template>
    <div>
        <SearcherHead
            :title="$t('category.title')"
            placeholder="Buscar por nombre..."
            @search="(x) => searcher.search(x)"
        >
            <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 Clasificación
            </button>
        </SearcherHead>

        <!-- Modal de Crear Categoría -->
        <CreateModal
            :show="showCreateModal"
            @close="closeCreateModal"
            @created="onCategorySaved"
        />

        <!-- Modal de Editar Categoría -->
        <EditModal
            :show="showEditModal"
            :category="editingCategory"
            @close="closeEditModal"
            @updated="onCategorySaved"
        />

        <!-- Modal de Eliminar Categoría -->
        <DeleteModal
            :show="showDeleteModal"
            :category="deletingCategory"
            @close="closeDeleteModal"
            @confirm="confirmDelete"
        />

        <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="router.push({ name: 'pos.category.subcategories', params: { id: model.id } })"
                                    class="text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
                                    title="Gestionar subclasificaciones"
                                >
                                    <GoogleIcon name="account_tree" class="text-xl" />
                                </button>
                                <button
                                    @click="openEditModal(model)"
                                    class="text-indigo-600 hover:text-indigo-900 transition-colors"
                                >
                                    <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 clasificació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">
                                {{ $t('registers.empty') }}
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
    </div>
</template>
