<script setup>
import { onMounted, ref } from 'vue';
import { useSearcher, apiURL } from '@Services/Api';
import { can } from './Module.js';

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


/** Estado */
const suppliers = ref([]);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingSupplier = ref(null);
const deletingSupplier = ref(null);

/** Métodos */
const searcher = useSearcher({
    url: apiURL('proveedores'),
    onSuccess: (r) => {
        suppliers.value = r.suppliers;
    },
    onError: () => suppliers.value = []
});

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

        if (response.ok) {
            window.Notify.success('Cliente eliminado exitosamente');
            closeDeleteModal();
            searcher.search();
        } else {
            window.Notify.error('Error al eliminar el cliente');
        }
    } catch (error) {
        console.error('Error:', error);
        window.Notify.error('Error al eliminar el cliente');
    }
};

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

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

const openEditModal = (supplier) => {
    editingSupplier.value = supplier;
    showEditModal.value = true;
};

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

const openDeleteModal = (supplier) => {
    deletingSupplier.value = supplier;
    showDeleteModal.value = true;
};

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

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

/** Ciclo de vida */
onMounted(() => {
    searcher.search();
});
</script>

<template>
    <div>
        <SearcherHead
            :title="$t('suppliers.title')"
            placeholder="Buscar por nombre..."
            @search="(x) => searcher.search(x)"
        >
            <button
                v-if="can('create')"
                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" />
                Nuevo Proveedor
            </button>
        </SearcherHead>
        <div class="pt-2 w-full">
            
            <Table
                :items="suppliers"
                @send-pagination="(page) => searcher.pagination(page)"
            >
                <template #head>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">NOMBRE</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">RFC</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">EMAIL</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">TELÉFONO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">DIRECCIÓN</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">CÓDIGO POSTAL</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">NOTAS</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="supplier in items"
                        :key="supplier.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ supplier.business_name }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ supplier.rfc }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ supplier.email }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ supplier.phone }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ supplier.address }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ supplier.postal_code }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ supplier.notes }}</p>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    v-if="can('edit')"
                                    @click.stop="openEditModal(supplier)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Editar proveedor"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="can('destroy')"
                                    @click.stop="openDeleteModal(supplier)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar proveedor"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="11" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                name="person"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                {{ $t('registers.empty') }}
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
        <!-- Modal de Crear Cliente -->
        <CreateModal
            v-if="can('create')"
            :show="showCreateModal"
            @close="closeCreateModal"
            @created="onSupplierSaved"
        />

        <!-- Modal de Editar Cliente -->
        <EditModal
            v-if="can('edit')"
            :show="showEditModal"
            :supplier="editingSupplier"
            @close="closeEditModal"
            @updated="onSupplierSaved"
        />

        <!-- Modal de Eliminar Proveedor -->
        <DeleteModal
            v-if="can('destroy')"
            :show="showDeleteModal"
            :supplier="deletingSupplier"
            @close="closeDeleteModal"
            @confirm="confirmDelete"
        />
    </div>
</template>