<script setup>
import { onMounted, onUnmounted, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSearcher, apiURL } from '@Services/Api';
import { page } from '@Services/Page';
import { formatCurrency } from '@/utils/formatters';
import useCart from '@Stores/cart';
import salesService from '@Services/salesService';
import ticketService from '@Services/ticketService';
import serialService from '@Services/serialService';

import GoogleIcon from '@Shared/GoogleIcon.vue';
import ProductCard from '@Components/POS/ProductCard.vue';
import CartItem from '@Components/POS/CartItem.vue';
import CheckoutModal from '@Components/POS/CheckoutModal.vue';
import ClientModal from '@Components/POS/ClientModal.vue';
import QRscan from '@Components/POS/QRscan.vue';
import SerialSelector from '@Components/POS/SerialSelector.vue';

/** i18n */
const { t } = useI18n();

/** Stores */
const cart = useCart();

/** Estado */
const products = ref([]);
const showCheckoutModal = ref(false);
const searchQuery = ref('');
const processingPayment = ref(false);
const scanMode = ref(false);
const showClientModal = ref(false);
const lastSaleData = ref(null);

// Estado para selector de seriales
const showSerialSelector = ref(false);
const serialSelectorProduct = ref(null);

/** Buscador de productos */
const searcher = useSearcher({
    url: apiURL('inventario'),
    onSuccess: (r) => {
        products.value = r.products?.data || [];
    },
    onError: () => {
        products.value = [];
        window.Notify.error(t('error.loading'));
    }
});

/** Computados */
const filteredProducts = computed(() => {
    if (!searchQuery.value) return products.value;

    const query = searchQuery.value.toLowerCase();
    return products.value.filter(product => {
        return (
            product.name?.toLowerCase().includes(query) ||
            product.sku?.toLowerCase().includes(query) ||
            product.barcode?.toLowerCase().includes(query) ||
            product.description?.toLowerCase().includes(query)
        );
    });
});

/** Métodos */
const addToCart = async (product) => {
    try {
        const response = await serialService.getAvailableSerials(product.id);

        const hasSerials = response.serials?.data?.length > 0;

        if (hasSerials) {
            // Agregar track_serials al producto para que el store lo reconozca
            product.track_serials = true;
            serialSelectorProduct.value = product;
            showSerialSelector.value = true;
            return;
        }

        cart.addProduct(product);
        window.Notify.success(`${product.name} agregado al carrito`);
    } catch (error) {
        // Si el API falla, agregar sin seriales
        cart.addProduct(product);
        window.Notify.success(`${product.name} agregado al carrito`);
    }
};

const closeSerialSelector = () => {
    showSerialSelector.value = false;
    serialSelectorProduct.value = null;
};

const handleSerialConfirm = (serialConfig) => {
    if (!serialSelectorProduct.value) return;

    cart.addProductWithSerials(
        serialSelectorProduct.value,
        serialConfig.quantity,
        serialConfig
    );

    window.Notify.success(`${serialSelectorProduct.value.name} agregado al carrito`);
    closeSerialSelector();
};

const handleClearCart = () => {
    if (confirm(t('cart.clearConfirm'))) {
        cart.clear();
        window.Notify.success('Carrito vaciado');
    }
};

const openCheckout = () => {
    if (cart.isEmpty) {
        window.Notify.error('El carrito está vacío');
        return;
    }
    showCheckoutModal.value = true;
};

const closeCheckout = () => {
    showCheckoutModal.value = false;
};

const toggleScanMode = () => {
    scanMode.value = !scanMode.value;
    if(scanMode.value) {
        window.Notify.info('Modo escaneo activado');
    } else {
        window.Notify.info('Modo escaneo desactivado');
    }
};

const handleCodeDetected = async (barcode) => {
    if (!barcode || barcode.trim() === '') {
        window.Notify.error('Código de barras inválido');
        return;
    }

    try {
        window.Notify.info('Buscando producto...');

        // Buscar producto por código de barras
        const response = await fetch(apiURL(`inventario?q=${encodeURIComponent(barcode)}`), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });

        const result = await response.json();

        // Verificar si se encontró el producto
        if (result.data && result.data.products && result.data.products.data && result.data.products.data.length > 0) {
            const product = result.data.products.data[0];

            // Verificar si el producto tiene stock
            if (product.stock <= 0) {
                window.Notify.error(`${product.name} no tiene stock disponible`);
                return;
            }

            // Agregar producto al carrito
            addToCart(product);
        } else {
            window.Notify.error('Producto no encontrado');
        }
    } catch (error) {
        console.error('Error buscando producto:', error);
        window.Notify.error('Error al buscar el producto');
    }
};

const handleConfirmSale = async (paymentData) => {
    processingPayment.value = true;

    try {
        // Establecer método de pago
        cart.setPaymentMethod(paymentData.paymentMethod);

        // Preparar datos de la venta
        const saleData = {
            user_id: page.user.id,
            subtotal: parseFloat(cart.subtotal.toFixed(2)),
            tax: parseFloat(cart.tax.toFixed(2)),
            total: parseFloat(cart.total.toFixed(2)), // El backend recalculará con descuento
            payment_method: paymentData.paymentMethod,
            items: cart.items.map(item => ({
                inventory_id: item.inventory_id,
                product_name: item.product_name,
                quantity: item.quantity,
                unit_price: item.unit_price,
                subtotal: parseFloat((item.quantity * item.unit_price).toFixed(2)),
                serial_numbers: item.track_serials ? (item.serial_numbers || []) : undefined
            }))
        };

        // Agregar client_number si se seleccionó un cliente
        if (paymentData.clientNumber) {
            saleData.client_number = paymentData.clientNumber;
        }

        // Agregar cash_received si es pago en efectivo
        if (paymentData.paymentMethod === 'cash' && paymentData.cashReceived) {
            saleData.cash_received = parseFloat(paymentData.cashReceived.toFixed(2));
        }

        // Crear venta
        window.Notify.info('Procesando venta...');
        const response = await salesService.createSale(saleData);

        // Mostrar información del descuento aplicado si hay
        if (response.discount_amount && parseFloat(response.discount_amount) > 0) {
            window.Notify.success(
                `¡Descuento aplicado! -$${parseFloat(response.discount_amount).toFixed(2)} (${parseFloat(response.discount_percentage).toFixed(2)}%)`,
                '',
                5
            );
        }

        // Detectar upgrade/downgrade de tier
        if (paymentData.clientData?.tier?.tier_name && response.client?.tier?.tier_name) {
            const oldTier = paymentData.clientData.tier.tier_name;
            const newTier = response.client.tier.tier_name;

            if (oldTier !== newTier) {
                window.Notify.success(
                    `¡El cliente subió de nivel! ${oldTier} → ${newTier} (${response.client.tier.discount_percentage}% descuento)`,
                    '',
                    8
                );
            }
        }

        // Mostrar mensaje de éxito con cambio si es efectivo
        if (paymentData.paymentMethod === 'cash' && response.change !== undefined) {
            window.Notify.success(
                `¡Venta realizada! Cambio: $${parseFloat(response.change).toFixed(2)}`,
                '',
                8
            );
        } else {
            window.Notify.success('¡Venta realizada exitosamente!');
        }

        if (response && response.id) {
            try {
                // Mostrar notificación de que se está generando el ticket
                window.Notify.info('Generando ticket...');

                // Generar ticket PDF con descarga automática
                await ticketService.generateSaleTicket(response, {
                    businessName: 'HIKVISION DISTRIBUIDOR',
                    autoDownload: true
                });

                // Notificación de éxito
                window.Notify.success('Ticket descargado correctamente');
            } catch (ticketError) {
                console.error('Error generando ticket:', ticketError);
                window.Notify.warning('Venta registrada, pero hubo un error al generar el ticket');
            }
        }

        lastSaleData.value = {
            id: response.id,
            total: saleData.total,
            payment_method: saleData.payment_method
        };

        // Limpiar carrito
        cart.clear();

        // Cerrar modal
        showCheckoutModal.value = false;

        // Recargar productos para actualizar stock
        searcher.search();

        // Solo mostrar modal de registro de cliente si NO se asoció un cliente a la venta
        if (!paymentData.clientNumber) {
            showClientModal.value = true;
        }

    } catch (error) {
        console.error('Error en venta:', error);

        // Manejar errores de validación
        if (error.status === 422 && error.errors) {
            const errorMessages = Object.values(error.errors).flat();
            errorMessages.forEach(msg => window.Notify.error(msg));
        } else {
            window.Notify.error(error.message || t('cart.error'));
        }
    } finally {
        processingPayment.value = false;
    }
};

const closeClientModal = () => {
    showClientModal.value = false;
    lastSaleData.value = null;
};

/** Event listener para abrir selector de seriales */
const handleOpenSerialSelector = (event) => {
    const productId = event.detail.productId;
    const product = products.value.find(p => p.id === productId);
    if (product) {
        serialSelectorProduct.value = product;
        showSerialSelector.value = true;
    }
};

/** Ciclo de vida */
onMounted(() => {
    searcher.search();
    // Escuchar evento personalizado para abrir selector de seriales
    window.addEventListener('open-serial-selector', handleOpenSerialSelector);
});

onUnmounted(() => {
    window.removeEventListener('open-serial-selector', handleOpenSerialSelector);
});
</script>

<template>
    <div class="h-full">
        <!-- Header -->
        <div class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 mb-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <GoogleIcon name="point_of_sale" class="text-3xl text-indigo-600 dark:text-indigo-400" />
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                            {{ $t('pos.title') }}
                        </h1>
                        <p class="text-sm text-gray-600 dark:text-gray-400">
                            {{ $t('pos.subtitle') }}
                        </p>
                    </div>
                </div>
                <button 
                @click="toggleScanMode"
                    :class="[
                        'flex items-center gap-2 px-4 py-3 rounded-lg font-semibold transition-all',
                        scanMode 
                            ? 'bg-red-500 hover:bg-red-600 text-white' 
                            : 'bg-indigo-500 hover:bg-indigo-600 text-white'
                    ]"
                    type="button"
                >
                    <GoogleIcon :name="scanMode ? 'close' : 'qr_code_scanner'" class="text-xl" />
                    {{ scanMode ? 'Cerrar escáner' : 'Escanear código' }}
                </button >
            </div>
        </div>

        <!-- Contenido Principal -->
        <div class="flex gap-6 h-[calc(100%-120px)] px-6">
            <!-- Columna de Productos -->
            <div class="flex-1 flex flex-col overflow-hidden">
                <div v-if="scanMode" class="h-full">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6 h-full">
                        <div class="flex flex-col h-full">
                            <h2 class="text-xl font-bold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
                                <GoogleIcon name="qr_code_scanner" class="text-2xl text-indigo-600" />
                                Escáner de Códigos de Barras
                            </h2>
                            <div class="flex-1 relative bg-gray-100 dark:bg-gray-900 rounded-lg overflow-hidden">
                                <QRscan 
                                    @qr-detected="handleCodeDetected"
                                    class="w-full h-full"
                                />
                            </div>
                            <div class="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                                <p class="text-sm text-blue-800 dark:text-blue-300">
                                    <strong>Instrucciones:</strong> Coloca el código de barras frente a la cámara. 
                                    El producto se agregará automáticamente al carrito cuando se detecte.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Buscador -->
                <div class="mb-4">
                    <div class="relative">
                        <input
                            v-model="searchQuery"
                            type="text"
                            placeholder="Buscar productos por nombre, SKU o código..."
                            class="w-full px-4 py-3 pl-12 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:text-gray-100"
                        />
                        <GoogleIcon
                            name="search"
                            class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-xl"
                        />
                    </div>
                </div>

                <!-- Grid de Productos -->
                <div class="flex-1 overflow-y-auto">
                    <div v-if="filteredProducts.length === 0" class="flex items-center justify-center h-full">
                        <div class="text-center">
                            <GoogleIcon name="inventory_2" class="text-6xl text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                            <p class="text-gray-500 dark:text-gray-400">
                                {{ searchQuery ? 'No se encontraron productos' : 'No hay productos disponibles' }}
                            </p>
                        </div>
                    </div>

                    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 pb-4">
                        <ProductCard
                            v-for="product in filteredProducts"
                            :key="product.id"
                            :product="product"
                            @add-to-cart="addToCart"
                        />
                    </div>
                </div>
            </div>

            <!-- Panel del Carrito -->
            <div class="w-96 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 flex flex-col">
                <!-- Header del Carrito -->
                <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <h2 class="text-lg font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                            <GoogleIcon name="shopping_cart" class="text-2xl text-indigo-600" />
                            {{ $t('cart.title') }}
                        </h2>
                        <span class="px-3 py-1 bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 text-sm font-semibold rounded-full">
                            {{ cart.itemCount }} {{ cart.itemCount === 1 ? 'item' : 'items' }}
                        </span>
                    </div>
                </div>

                <!-- Items del Carrito -->
                <div class="flex-1 overflow-y-auto p-4 space-y-3">
                    <div v-if="cart.isEmpty" class="flex flex-col items-center justify-center h-full text-center py-12">
                        <GoogleIcon name="shopping_cart" class="text-6xl text-gray-300 dark:text-gray-600 mb-4" />
                        <p class="text-gray-500 dark:text-gray-400 font-medium">
                            {{ $t('cart.empty') }}
                        </p>
                        <p class="text-sm text-gray-400 dark:text-gray-500 mt-2">
                            {{ $t('cart.emptyMessage') }}
                        </p>
                    </div>

                    <CartItem
                        v-for="item in cart.items"
                        :key="item.inventory_id"
                        :item="item"
                        @update-quantity="cart.updateQuantity"
                        @remove="cart.removeProduct"
                    />
                </div>

                <!-- Resumen y Botones -->
                <div class="p-4 border-t border-gray-200 dark:border-gray-700 space-y-4">
                    <!-- Totales -->
                    <div class="space-y-2">
                        <div class="flex justify-between text-sm text-gray-600 dark:text-gray-400">
                            <span>{{ $t('cart.subtotal') }}</span>
                            <span class="font-semibold">${{ formatCurrency(cart.subtotal) }}</span>
                        </div>
                        <div class="flex justify-between text-sm text-gray-600 dark:text-gray-400">
                            <span>IVA (16%)</span>
                            <span class="font-semibold">${{ formatCurrency(cart.tax) }}</span>
                        </div>
                        <div class="pt-2 border-t border-gray-200 dark:border-gray-700">
                            <div class="flex justify-between items-center">
                                <span class="text-base font-bold text-gray-900 dark:text-gray-100">
                                    {{ $t('cart.total') }}
                                </span>
                                <span class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">
                                    {{ formatCurrency(cart.total) }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- Botones de Acción -->
                    <div class="space-y-2">
                        <button
                            type="button"
                            class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white text-base font-semibold rounded-lg transition-colors shadow-lg"
                            :disabled="cart.isEmpty"
                            @click="openCheckout"
                        >
                            <GoogleIcon name="point_of_sale" class="text-xl" />
                            {{ $t('cart.checkout') }}
                        </button>

                        <button
                            type="button"
                            class="w-full flex items-center justify-center gap-2 px-4 py-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:text-gray-400 disabled:cursor-not-allowed text-sm font-semibold rounded-lg transition-colors"
                            :disabled="cart.isEmpty"
                            @click="handleClearCart"
                        >
                            <GoogleIcon name="delete_sweep" class="text-lg" />
                            {{ $t('cart.clear') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Checkout -->
        <CheckoutModal
            :show="showCheckoutModal"
            :cart="cart"
            :processing="processingPayment"
            @close="closeCheckout"
            @confirm="handleConfirmSale"
        />
        <ClientModal
            :show="showClientModal"
            :sale-data="lastSaleData"
            @close="closeClientModal"
        />

        <!-- Modal de Selección de Seriales -->
        <SerialSelector
            v-if="serialSelectorProduct"
            :show="showSerialSelector"
            :product="serialSelectorProduct"
            :exclude-serials="cart.getSelectedSerials()"
            @close="closeSerialSelector"
            @confirm="handleSerialConfirm"
        />
    </div>
</template>
