<script setup>
import { onMounted, ref } from 'vue';
import { useSearcher, apiURL } from '@Services/Api';
import ticketService from '@Services/ticketService';
import { formatCurrency, formatDate, PAYMENT_METHODS } from '@/utils/formatters';

import SearcherHead from '@Holos/Searcher.vue';
import Table from '@Holos/Table.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import SaleDetailModal from './DetailModal.vue';
import ExcelModal from '@Components/POS/ExcelSale.vue';

/** Estado */
const models = ref([]);
const showDetailModal = ref(false);
const selectedSale = ref(null);
const showExcelModal = ref(false);

/** Buscador de ventas */
const searcher = useSearcher({
    url: apiURL('sales'),
    onSuccess: (r) => {
        models.value = r.sales || r.models || { data: [], total: 0 };
    },
    onError: (error) => {
        console.error('❌ ERROR al cargar ventas:', error);
        models.value = { data: [], total: 0 };
        window.Notify.error('Error al cargar ventas');
    }
});

/** Métodos */
const openDetailModal = (sale) => {
    selectedSale.value = sale;
    showDetailModal.value = true;
};

const closeDetailModal = () => {
    showDetailModal.value = false;
    selectedSale.value = null;
};

const openExcelModal = () => {
    showExcelModal.value = true;
};

const closeExcelModal = () => {
    showExcelModal.value = false;
};

const handleCancelSale = async (saleId) => {
    if (!confirm('¿Estás seguro de cancelar esta venta? Se restaurará el stock.')) {
        return;
    }

    try {
        const response = await fetch(apiURL(`sales/${saleId}/cancel`), {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            window.Notify.success('Venta cancelada exitosamente');
            closeDetailModal();
            searcher.search();
        } else {
            window.Notify.error('Error al cancelar la venta');
        }
    } catch (error) {
        console.error('Error:', error);
        window.Notify.error('Error al cancelar la venta');
    }
};

const getPaymentMethodLabel = (method) => {
    return PAYMENT_METHODS[method] || method;
};

const getStatusColor = (status) => {
    return status === 'completed'
        ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
        : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400';
};

const getStatusLabel = (status) => {
    return status === 'completed' ? 'Completada' : 'Cancelada';
};

const handleDownloadTicket = (sale) => {
    try {
        ticketService.generateSaleTicket(sale, {
            autoDownload: true
        });
        window.Notify.success('Ticket descargado correctamente');
    } catch (error) {
        console.error('Error generando ticket:', error);
        window.Notify.error('Error al generar el ticket PDF');
    }
};

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

<template>
    <div>
        <SearcherHead
            :title="$t('sales.title')"
            placeholder="Buscar por folio o cajero..."
            @search="(x) => searcher.search(x)"
        >
            <button
                class="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                @click="openExcelModal"
            >
                <GoogleIcon name="add" class="text-xl" />
                Generar excel
            </button>
        </SearcherHead>
        <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">FOLIO</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">FECHA</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">CAJERO</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">MÉTODO DE PAGO</th>
                    <th class="px-6 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">TOTAL</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="model in items"
                        :key="model.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm font-mono font-semibold text-gray-900 dark:text-gray-100">
                                #{{ model.invoice_number }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                {{ formatDate(model.created_at) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                {{ model.user?.name || '-' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center gap-2">
                                <GoogleIcon
                                    :name="model.payment_method === 'cash' ? 'payments' : 'credit_card'"
                                    class="text-gray-500 dark:text-gray-400"
                                />
                                <span class="text-sm text-gray-700 dark:text-gray-300">
                                    {{ getPaymentMethodLabel(model.payment_method) }}
                                </span>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right">
                            <span class="text-sm font-bold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(model.total) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span
                                class="inline-flex px-3 py-1 text-xs font-semibold rounded-full"
                                :class="getStatusColor(model.status)"
                            >
                                {{ getStatusLabel(model.status) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    @click="openDetailModal(model)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Ver detalles"
                                >
                                    <GoogleIcon name="visibility" class="text-xl" />
                                </button>
                                <button
                                    @click="handleDownloadTicket(model)"
                                    class="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300 transition-colors"
                                    title="Descargar ticket PDF"
                                >
                                    <GoogleIcon name="download" 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="receipt_long"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                {{ $t('sales.empty') }}
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
    </div>

    <!-- Modal de Detalle -->
    <SaleDetailModal
        :show="showDetailModal"
        :sale="selectedSale"
        @close="closeDetailModal"
        @cancel-sale="handleCancelSale"
    />

    <!-- Modal de Excel de Clientes -->
    <ExcelModal
        :show="showExcelModal"
        @close="closeExcelModal"
    />

</template>
