/**
 * Barcode Scanner Integration for POS System
 * Connects the barcode scanner to the sales cart
 */

(function() {
    'use strict';

    let scannerInstance = null;
    let productCache = {}; // Cache for recently scanned products
    const CACHE_SIZE = 50; // Maximum products to cache
    const CACHE_EXPIRY = 300000; // 5 minutes in milliseconds

    /**
     * Initialize barcode scanner button
     */
    function initBarcodeScannerButton() {
        // Add camera icon to the barcode input button
        const barcodeInput = $('#productCode'); // Changed from productBarcode to productCode
        const barcodeInputGroup = barcodeInput.closest('.input-group');
        
        // Check if button already exists
        if ($('#mobileScanBtn').length > 0) {
            return;
        }

        // Create scan button with camera icon
        const scanButton = $(`
            <div class="input-group-append">
                <button class="btn btn-primary btn-sm camera-scan-btn" type="button" id="mobileScanBtn" title="Scan with Camera">
                    <i class="fas fa-camera camera-icon"></i>
                </button>
            </div>
        `);

        // Insert button after input
        barcodeInputGroup.append(scanButton);

        // Bind click event
        $('#mobileScanBtn').on('click', async function(e) {
            e.preventDefault();
            await startScanner();
        });

        // Also allow Enter key on barcode input to trigger normal search
        barcodeInput.on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                const code = $(this).val().trim();
                if (code) {
                    searchProductByCode(code);
                }
            }
        });
    }

    /**
     * Start the barcode scanner
     */
    async function startScanner() {
        // Check if html5-qrcode scanner function exists
        if (typeof startBarcodeScanner === 'function') {
            startBarcodeScanner();
            return;
        }

        // Fallback error message
        await MsgBox.alert('Barcode scanner not available. Please refresh the page.');
    }

    /**
     * Handle successful barcode scan
     */
    function handleScanSuccess(code, format) {
        console.log(`Scanned code: ${code}, format: ${format}`);

        // Immediate visual feedback - show scanning success
        showImmediateScanFeedback(code);

        // Update barcode input field
        $('#productCode').val(code);

        // Search for product by code
        searchProductByCode(code);
    }

    /**
     * Handle scanner errors
     */
    function handleScanError(error) {
        console.error('Scanner error:', error);
        
        // Show user-friendly error message
        let message = 'Scanner error occurred';
        if (error.message) {
            message = error.message;
        }
        
        showNotification(message, 'error');
    }

    /**
     * Add product to cache
     */
    function addToCache(code, product) {
        const cacheKey = code.toLowerCase().trim();
        productCache[cacheKey] = {
            data: product,
            timestamp: Date.now()
        };

        // Clean up old cache entries if we exceed the limit
        const cacheKeys = Object.keys(productCache);
        if (cacheKeys.length > CACHE_SIZE) {
            // Remove oldest entries
            const sortedKeys = cacheKeys.sort((a, b) => productCache[a].timestamp - productCache[b].timestamp);
            const keysToRemove = sortedKeys.slice(0, cacheKeys.length - CACHE_SIZE);
            keysToRemove.forEach(key => delete productCache[key]);
        }
    }

    /**
     * Get product from cache
     */
    function getFromCache(code) {
        const cacheKey = code.toLowerCase().trim();
        const cached = productCache[cacheKey];

        if (cached && (Date.now() - cached.timestamp) < CACHE_EXPIRY) {
            return cached.data;
        } else if (cached) {
            // Remove expired entry
            delete productCache[cacheKey];
        }

        return null;
    }

    /**
     * Clear product cache
     */
    function clearProductCache() {
        productCache = {};
    }
    /**
     * Search for product by barcode/code
     */
    function searchProductByCode(code) {
        if (!code || code.trim() === '') {
            showNotification('Please enter a valid code', 'warning');
            return;
        }

        code = code.trim();

        // Check cache first
        const cachedProduct = getFromCache(code);
        if (cachedProduct) {
            console.log('Product found in cache:', cachedProduct);
            addProductToCart(cachedProduct);
            showNotification(`Added: ${cachedProduct.name}`, 'success');
            $('#productCode').val('').focus();
            return;
        }

        // Show loading state
        const originalHtml = $('#mobileScanBtn').html();
        $('#mobileScanBtn').html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);

        // Make AJAX request to search for product
        $.ajax({
            url: 'api/search-product-by-code.php',
            method: 'POST',
            data: { 
                code: code,
                salesType: $('#currentSalesType').val() || 'GST'
            },
            dataType: 'json',
            success: function(response) {
                $('#mobileScanBtn').html(originalHtml).prop('disabled', false);

                if (response.success) {
                    if (response.multiple && response.products.length > 1) {
                        // Multiple products found - show selection modal
                        showProductSelection(response.products);
                    } else if (response.product) {
                        // Single product found - add to cart
                        const product = response.product;
                        addToCache(code, product); // Cache the product
                        addProductToCart(product);
                        showNotification(`Added: ${product.name}`, 'success');
                        
                        // Clear barcode input
                        $('#productCode').val('').focus();
                    } else {
                        showNotification('Product not found', 'warning');
                    }
                } else {
                    showNotification(response.message || 'Product not found', 'error');
                }
            },
            error: function(xhr, status, error) {
                $('#mobileScanBtn').html(originalHtml).prop('disabled', false);
                console.error('Search error:', error);
                showNotification('Error searching for product', 'error');
            }
        });
    }

    /**
     * Add product to cart
     */
    function addProductToCart(product) {
        // Check if addToCart function exists in sales.js
        if (typeof window.addToCart === 'function') {
            window.addToCart(product);
        } else if (typeof addItemToCart === 'function') {
            addItemToCart(product);
        } else {
            // Manual cart addition if function doesn't exist
            console.log('Adding to cart:', product);
            
            // Trigger product addition via existing mechanism
            if (typeof cart !== 'undefined' && Array.isArray(cart)) {
                cart.push({
                    productId: product.id,
                    productCode: product.code,
                    productName: product.name,
                    rate: parseFloat(product.price || 0),
                    quantity: 1,
                    discount: 0,
                    discountType: 'PERCENTAGE',
                    amount: parseFloat(product.price || 0),
                    taxPercent: parseFloat(product.tax || 0)
                });

                // Update display
                if (typeof updateDisplay === 'function') {
                    updateDisplay();
                }
            }
        }
    }

    /**
     * Show product selection modal for multiple matches
     */
    function showProductSelection(products) {
        const modalBody = $('#productSelectionList');
        modalBody.empty();

        products.forEach((product, index) => {
            const row = $(`
                <tr class="product-selection-row" data-index="${index}" style="cursor: pointer;">
                    <td>${product.code}</td>
                    <td>${product.name}</td>
                    <td>${product.category || '-'}</td>
                    <td class="text-right">₹${parseFloat(product.price || 0).toFixed(2)}</td>
                    <td class="text-center">${parseFloat(product.stock || 0).toFixed(2)}</td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-primary select-product-btn" data-index="${index}">
                            <i class="fas fa-check"></i> Select
                        </button>
                    </td>
                </tr>
            `);

            modalBody.append(row);
        });

        // Bind selection events
        $('.select-product-btn, .product-selection-row').on('click', function(e) {
            e.preventDefault();
            const index = $(this).data('index');
            const selectedProduct = products[index];
            
            addProductToCart(selectedProduct);
            showNotification(`Added: ${selectedProduct.name}`, 'success');
            
            $('#productSelectionModal').modal('hide');
            $('#productCode').val('').focus(); // Changed from productBarcode to productCode
        });

        // Show modal
        $('#productSelectionModal').modal('show');
    }

    /**
     * Show immediate scan feedback
     */
    function showImmediateScanFeedback(code) {
        // Create immediate feedback overlay
        const feedback = $(`
            <div class="scan-feedback-overlay" style="
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(40, 167, 69, 0.1);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 9998;
                animation: fadeInOut 0.8s ease;
            ">
                <div class="scan-feedback-content" style="
                    background: white;
                    padding: 20px 30px;
                    border-radius: 12px;
                    box-shadow: 0 8px 32px rgba(0,0,0,0.2);
                    text-align: center;
                    border: 3px solid #28a745;
                ">
                    <div class="scan-success-icon" style="
                        font-size: 48px;
                        color: #28a745;
                        margin-bottom: 10px;
                    ">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="scan-code-display" style="
                        font-size: 18px;
                        font-weight: bold;
                        color: #28a745;
                        margin-bottom: 5px;
                    ">
                        ${code}
                    </div>
                    <div class="scan-status-text" style="
                        color: #6c757d;
                        font-size: 14px;
                    ">
                        Searching product...
                    </div>
                </div>
            </div>
        `);

        // Add fadeInOut animation
        if (!$('#scan-feedback-styles').length) {
            $('head').append(`
                <style id="scan-feedback-styles">
                    @keyframes fadeInOut {
                        0% { opacity: 0; }
                        20% { opacity: 1; }
                        80% { opacity: 1; }
                        100% { opacity: 0; }
                    }
                </style>
            `);
        }

        $('body').append(feedback);

        // Play success beep immediately
        playScanBeep();

        // Remove after animation
        setTimeout(() => {
            feedback.remove();
        }, 800);
    }

    /**
     * Play beep sound for successful scan
     */
    function playScanBeep() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);

            oscillator.frequency.value = 1000; // Higher pitch for scan success
            oscillator.type = 'sine';

            gainNode.gain.setValueAtTime(0.2, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.15);

            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.15);
        } catch (e) {
            console.warn('Could not play scan beep sound:', e);
        }
    }

    /**
     * Show scanning feedback
     */
    function showScanningFeedback(message) {
        // You can customize this based on your UI
        const toast = $(`
            <div class="scanning-toast">
                <i class="fas fa-search"></i> ${message}
            </div>
        `);

        $('body').append(toast);

        setTimeout(() => {
            toast.fadeOut(300, function() {
                $(this).remove();
            });
        }, 2000);
    }

    /**
     * Show notification
     */
    function showNotification(message, type = 'info') {
        // Check if notification function exists
        if (typeof showToast === 'function') {
            showToast(message, type);
            return;
        }

        // Fallback notification
        const bgColor = {
            'success': '#1cc88a',
            'error': '#e74a3b',
            'warning': '#f6c23e',
            'info': '#4e73df'
        }[type] || '#4e73df';

        const icon = {
            'success': 'check-circle',
            'error': 'exclamation-circle',
            'warning': 'exclamation-triangle',
            'info': 'info-circle'
        }[type] || 'info-circle';

        const notification = $(`
            <div class="scanner-notification" style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${bgColor};
                color: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                z-index: 9999;
                display: flex;
                align-items: center;
                gap: 10px;
                min-width: 250px;
                animation: slideInRight 0.3s ease;
            ">
                <i class="fas fa-${icon}" style="font-size: 18px;"></i>
                <span>${message}</span>
            </div>
        `);

        $('body').append(notification);

        setTimeout(() => {
            notification.fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }

    /**
     * Add CSS animation for notification
     */
    function addNotificationStyles() {
        if ($('#scanner-notification-styles').length > 0) return;

        const styles = $(`
            <style id="scanner-notification-styles">
                @keyframes slideInRight {
                    from {
                        transform: translateX(100%);
                        opacity: 0;
                    }
                    to {
                        transform: translateX(0);
                        opacity: 1;
                    }
                }

                .scanning-toast {
                    position: fixed;
                    top: 80px;
                    left: 50%;
                    transform: translateX(-50%);
                    background: rgba(78, 115, 223, 0.95);
                    color: white;
                    padding: 12px 24px;
                    border-radius: 25px;
                    z-index: 9999;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    font-size: 14px;
                    animation: slideInDown 0.3s ease;
                }

                @keyframes slideInDown {
                    from {
                        transform: translate(-50%, -100%);
                        opacity: 0;
                    }
                    to {
                        transform: translate(-50%, 0);
                        opacity: 1;
                    }
                }

                @media (max-width: 576px) {
                    .scanner-notification {
                        top: 10px !important;
                        right: 10px !important;
                        left: 10px !important;
                        min-width: auto !important;
                    }
                }
            </style>
        `);

        $('head').append(styles);
    }

    /**
     * Initialize on document ready
     */
    $(document).ready(function() {
        // Add notification styles
        addNotificationStyles();

        // Initialize scanner button
        initBarcodeScannerButton();

        // Listen for barcode scanned event from main scanner
        $(document).on('barcodeScanned', function(e, barcode) {
            handleScanSuccess(barcode, 'QR_CODE');
        });

        // Keyboard shortcut: Ctrl/Cmd + K to open scanner
        $(document).on('keydown', async function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                await startScanner();
            }
        });

        console.log('Barcode Scanner Integration initialized');
    });

    // Export functions for global access
    window.startBarcodeScanner = startScanner;
    window.searchProductByCode = searchProductByCode;

})();
