<script setup>
import { onMounted, ref } from 'vue';
import { api, 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';

/** Estado */
const units = ref([]);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const editingUnit = ref(null);

/** Búsqueda / paginación */
const searcher = useSearcher({
    url: apiURL('unidades-medida'),
    onSuccess: (r) => {
        units.value = r.units;
    },
    onError: () => { units.value = []; }
});

/** Métodos */
const openCreateModal = () => { showCreateModal.value = true; };
const closeCreateModal = () => { showCreateModal.value = false; };

const openEditModal = (unit) => {
    editingUnit.value = unit;
    showEditModal.value = true;
};

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

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

const deleteUnit = (unit) => {
    if (!confirm(`¿Eliminar la unidad "${unit.name}"? Esta acción no se puede deshacer.`)) return;

    api.delete(apiURL(`unidades-medida/${unit.id}`), {
        onSuccess: () => {
            window.Notify.success('Unidad de medida eliminada');
            searcher.search();
        },
        onFail: (data) => {
            window.Notify.error(data.message || 'No se puede eliminar esta unidad porque está en uso');
        },
        onError: () => {
            window.Notify.error('Error de conexión al eliminar la unidad');
        }
    });
};

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

<template>
    <div>
        <SearcherHead
            title="Unidades de Medida"
            placeholder="Buscar por nombre o abreviación..."
            @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" />
                Nueva Unidad
            </button>
        </SearcherHead>

        <div class="pt-2 w-full">
            <Table
                :items="units"
                @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-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ABREVIACIÓN</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">DECIMALES</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="unit in items"
                        :key="unit.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">{{ unit.name }}</p>
                        </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-mono font-semibold bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">
                                {{ unit.abbreviation }}
                            </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',
                                    unit.allows_decimals
                                        ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
                                        : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300'
                                ]"
                            >
                                {{ unit.allows_decimals ? 'Sí' : 'No' }}
                            </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',
                                    unit.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'
                                ]"
                            >
                                {{ unit.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
                                    v-if="can('edit')"
                                    @click="openEditModal(unit)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Editar unidad"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="can('destroy')"
                                    @click="deleteUnit(unit)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar unidad"
                                >
                                    <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="straighten" class="text-6xl mb-2 opacity-50" />
                            <p class="font-semibold">No hay unidades de medida registradas</p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

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

        <!-- Modal Editar -->
        <EditModal
            v-if="can('edit')"
            :show="showEditModal"
            :unit="editingUnit"
            @close="closeEditModal"
            @updated="onUnitSaved"
        />
    </div>
</template>
