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

const router = useRouter();

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 warehouses = ref([]);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingWarehouse = ref(null);
const deletingWarehouse = ref(null);

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

const confirmDelete = (id) => {
    api.delete(apiURL(`almacenes/${id}`), {
        onSuccess: () => {
            window.Notify.success('Almacén eliminado exitosamente');
            closeDeleteModal();
            searcher.search();
        },
        onFail: (data) => {
            window.Notify.error(data.message || 'No se puede eliminar el almacén porque tiene stock');
        },
        onError: () => {
            window.Notify.error('Error de conexión al eliminar el almacén');
        }
    });
};

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

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

const openEditModal = (warehouse) => {
    editingWarehouse.value = warehouse;
    showEditModal.value = true;
};

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

const openDeleteModal = (warehouse) => {
    deletingWarehouse.value = warehouse;
    showDeleteModal.value = true;
};

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

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

const viewInventory = (warehouse) => {
    router.push({ name: 'pos.warehouses.inventory', params: { id: warehouse.id } });
};

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

<template>
    <div>
        <SearcherHead
            :title="$t('warehouses.title')"
            placeholder="Buscar por nombre o código..."
            @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 Almacén
            </button>
        </SearcherHead>
        <div class="pt-2 w-full">

            <Table
                :items="warehouses"
                @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">CÓDIGO</th>
                    <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">PRINCIPAL</th>
                    <th class="px-6 py-3 text-center 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="warehouse in items"
                        :key="warehouse.id"
                        @click="viewInventory(warehouse)"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer"
                    >
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-mono font-semibold text-gray-900 dark:text-gray-100">{{ warehouse.code }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ warehouse.name }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <span
                                v-if="warehouse.is_main"
                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
                            >
                                <GoogleIcon name="star" class="text-sm mr-1" />
                                Principal
                            </span>
                            <span v-else class="text-sm text-gray-400 dark:text-gray-500">—</span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <span
                                :class="[
                                    'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
                                    warehouse.is_active
                                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                                        : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                                ]"
                            >
                                {{ warehouse.is_active ? 'Activo' : 'Inactivo' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center" @click.stop>
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    v-if="can('edit')"
                                    @click="openEditModal(warehouse)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Editar almacén"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="can('destroy')"
                                    @click="openDeleteModal(warehouse)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar almacén"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="5" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                name="warehouse"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                {{ $t('registers.empty') }}
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

        <!-- Modal de Crear Almacén -->
        <CreateModal
            v-if="can('create')"
            :show="showCreateModal"
            @close="closeCreateModal"
            @created="onWarehouseSaved"
        />

        <!-- Modal de Editar Almacén -->
        <EditModal
            v-if="can('edit')"
            :show="showEditModal"
            :warehouse="editingWarehouse"
            @close="closeEditModal"
            @updated="onWarehouseSaved"
        />

        <!-- Modal de Eliminar Almacén -->
        <DeleteModal
            v-if="can('destroy')"
            :show="showDeleteModal"
            :warehouse="deletingWarehouse"
            @close="closeDeleteModal"
            @confirm="confirmDelete"
        />
    </div>
</template>
