<script setup>
import { onMounted, ref } from 'vue';
import { api, useSearcher, apiURL } from '@Services/Api';
import { can } from './Module.js';
import { formatCurrency, formatPercent } from '@/utils/formatters.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';
import ToggleButton from '@Components/POS/Tiers/ToggleButton.vue';


/** Estado */
const tiers = ref([]);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingClient = ref(null);
const deletingClient = ref(null);

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

/** Métodos auxiliares */
const onToggled = () => {
    searcher.search();
};

const confirmDelete = (id) => {
    api.delete(apiURL(`client-tiers/${id}`), {
        onSuccess: () => {
            window.Notify.success('Nivel de cliente eliminado exitosamente');
            closeDeleteModal();
            searcher.search();
        },
        onFail: (data) => {
            window.Notify.error(data.message || 'No se puede eliminar el nivel porque tiene clientes asignados');
        },
        onError: () => {
            window.Notify.error('Error de conexión al eliminar el nivel');
        }
    });
};

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

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

const openEditModal = (client) => {
    editingClient.value = client;
    showEditModal.value = true;
};

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

const openDeleteModal = (client) => {
    deletingClient.value = client;
    showDeleteModal.value = true;
};

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

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

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

<template>
    <div>
        <SearcherHead
            :title="$t('clientTiers.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 Nivel
            </button>
        </SearcherHead>
        <div class="pt-2 w-full">

            <Table
                :items="tiers"
                @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">CANTIDAD MINIMA ACUMULADA</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">CANTIDAD MÁXIMA ACUMULADA</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">DESCUENTOS</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">CLIENTES</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="tier in items"
                        :key="tier.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">{{ tier.tier_name }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ formatCurrency(tier.min_purchase_amount) }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ tier.max_purchase_amount ? formatCurrency(tier.max_purchase_amount) : 'Sin límite' }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">{{ formatPercent(tier.discount_percentage) }}</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-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200">
                                {{ tier.clients_count || 0 }}
                            </span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <ToggleButton
                                :tier="tier"
                                @toggled="onToggled"
                            />
                        </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(tier)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Editar nivel"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="can('destroy')"
                                    @click.stop="openDeleteModal(tier)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar nivel"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="7" 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="onClientSaved"
        />

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

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