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

import Modal from '@Holos/Modal.vue';
import SearcherHead from '@Holos/Searcher.vue';
import Table from '@Holos/Table.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    }
});

/** Emits */
const emit = defineEmits(['close', 'select-sale']);

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

/** Buscador de ventas completadas */
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');
    }
});

/** Watchers */
watch(() => props.show, (isShown) => {
    if (isShown) {
        selectedSale.value = null;
        searcher.search();
    }
});

/** Métodos */
const handleSearch = (query) => {
    searcher.search({ q: query, status: 'completed' });
};

const selectSale = (sale) => {
    selectedSale.value = sale;
};

const isSelected = (sale) => {
    return selectedSale.value?.id === sale.id;
};

const confirmSelection = () => {
    if (!selectedSale.value) {
        window.Notify.warning('Selecciona una venta para continuar');
        return;
    }
    emit('select-sale', selectedSale.value);
};

const handleClose = () => {
    selectedSale.value = null;
    emit('close');
};

/** Helpers de método de pago */
const getPaymentMethodLabel = (method) => {
    const labels = {
        cash: 'Efectivo',
        card: 'Debito',
        credit: 'Crédito'
    };
    return labels[method] || method || '-';
};

const getPaymentMethodIcon = (method) => {
    const icons = {
        cash: 'payments',
        card: 'credit_card',
        credit: 'request_quote'
    };
    return icons[method] || 'payment';
};
</script>

<template>
    <Modal :show="show" max-width="4xl" @close="handleClose">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-xl flex items-center justify-center">
                        <GoogleIcon name="receipt_long" class="text-2xl text-indigo-600 dark:text-indigo-400" />
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                            Seleccionar Venta
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            Busca y selecciona la venta original para la devolución
                        </p>
                    </div>
                </div>
                <button
                    @click="handleClose"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                    <GoogleIcon name="close" class="text-2xl" />
                </button>
            </div>

            <!-- Buscador -->
            <div class="mb-4">
                <SearcherHead
                    title=""
                    placeholder="Buscar por folio, cliente o cajero..."
                    @search="handleSearch"
                />
            </div>

            <!-- Venta seleccionada preview -->
            <div
                v-if="selectedSale"
                class="mb-4 bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800 rounded-lg p-4"
            >
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <GoogleIcon name="check_circle" class="text-2xl text-indigo-600 dark:text-indigo-400" />
                        <div>
                            <p class="text-sm text-indigo-600 dark:text-indigo-400">Venta seleccionada:</p>
                            <p class="font-semibold text-indigo-700 dark:text-indigo-300 font-mono">
                                #{{ selectedSale.invoice_number || selectedSale.id }}
                            </p>
                        </div>
                    </div>
                    <p class="text-lg font-bold text-indigo-700 dark:text-indigo-300">
                        {{ formatCurrency(selectedSale.total) }}
                    </p>
                </div>
            </div>

            <!-- Tabla de ventas -->
            <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                <Table
                    :items="models"
                    :processing="searcher.processing"
                    @send-pagination="(page) => searcher.pagination(page)"
                >
                    <template #head>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase w-10">
                            <span class="sr-only">Seleccionar</span>
                        </th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Folio
                        </th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Fecha
                        </th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Cajero
                        </th>
                        <th class="px-4 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Método de Pago
                        </th>
                        <th class="px-4 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                            Total
                        </th>
                    </template>
                    <template #body="{ items }">
                        <tr
                            v-for="sale in items"
                            :key="sale.id"
                            @click="selectSale(sale)"
                            class="cursor-pointer transition-colors"
                            :class="isSelected(sale)
                                ? 'bg-indigo-50 dark:bg-indigo-900/30 hover:bg-indigo-100 dark:hover:bg-indigo-900/40'
                                : 'hover:bg-gray-50 dark:hover:bg-gray-800'"
                        >
                            <td class="px-4 py-3">
                                <input
                                    type="radio"
                                    :checked="isSelected(sale)"
                                    @change="selectSale(sale)"
                                    class="w-4 h-4 text-indigo-600 border-gray-300 focus:ring-indigo-500"
                                />
                            </td>
                            <td class="px-4 py-3">
                                <span class="text-sm font-mono font-semibold text-indigo-600 dark:text-indigo-400">
                                    #{{ sale.invoice_number || sale.id }}
                                </span>
                            </td>
                            <td class="px-4 py-3">
                                <span class="text-sm text-gray-700 dark:text-gray-300">
                                    {{ formatDate(sale.created_at) }}
                                </span>
                            </td>
                            <td class="px-4 py-3">
                                <span class="text-sm text-gray-700 dark:text-gray-300">
                                    {{ sale.user?.name || sale.cashier?.name || '-' }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                    <GoogleIcon :name="getPaymentMethodIcon(sale.payment_method)" class="text-sm" />
                                    {{ getPaymentMethodLabel(sale.payment_method) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-right">
                                <span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                    {{ formatCurrency(sale.total) }}
                                </span>
                            </td>
                        </tr>
                    </template>
                    <template #empty>
                        <td colspan="6" 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">No hay ventas disponibles</p>
                                <p class="text-sm mt-1">Intenta buscar con otros términos</p>
                            </div>
                        </td>
                    </template>
                </Table>
            </div>

            <!-- Footer -->
            <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button
                    type="button"
                    class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 text-sm font-semibold rounded-lg transition-colors"
                    @click="handleClose"
                >
                    Cancelar
                </button>
                <button
                    type="button"
                    :disabled="!selectedSale"
                    class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 disabled:cursor-not-allowed text-white text-sm font-semibold rounded-lg transition-colors flex items-center gap-2"
                    @click="confirmSelection"
                >
                    <GoogleIcon name="arrow_forward" />
                    Continuar
                </button>
            </div>
        </div>
    </Modal>
</template>