/**
 * Barcode Scanner Integration for Add Item Page
 * Uses ZXing WebAssembly for barcode/QR code scanning
 */

(function() {
    'use strict';

    let scannerInstance = null;

    /**
     * Initialize barcode scanner button
     */
    function initBarcodeScanner() {
        const scanButton = $('#scanBarcodeBtn');
        
        if (scanButton.length === 0) {
            console.warn('Scan barcode button not found');
            return;
        }

        // Bind click event to scan button
        scanButton.on('click', function(e) {
            e.preventDefault();
            startScanner();
        });

        // Add keyboard shortcut (Ctrl/Cmd + B for Barcode)
        $(document).on('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
                e.preventDefault();
                startScanner();
            }
        });

        console.log('Barcode scanner initialized for Add Item page');
    }

    /**
     * Start the barcode scanner
     */
    function startScanner() {
        // Check if ZXing library is loaded
        if (typeof ZXing === 'undefined') {
            showNotification('Barcode scanner library not loaded. Please refresh the page.', 'error');
            return;
        }

        // Check if scanner class is available
        if (typeof BarcodeScanner === 'undefined') {
            showNotification('Barcode scanner not initialized. Please refresh the page.', 'error');
            return;
        }

        // Check if device has camera
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            showNotification('Camera not supported on this device or browser.', 'error');
            return;
        }

        // Create scanner instance if not exists
        if (!scannerInstance) {
            scannerInstance = new BarcodeScanner({
                onSuccess: handleScanSuccess,
                onError: handleScanError,
                preferredCamera: 'environment' // Rear camera for mobile
            });
        }

        // Start scanning
        scannerInstance.start().catch(err => {
            console.error('Failed to start scanner:', err);
            handleScanError(err);
        });
    }

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

        // Update barcode input field
        $('#barcodeInput').val(code).trigger('change');

        // Show success notification
        showNotification(`Barcode scanned: ${code}`, 'success');

        // Focus on the next field (you can change this to any field)
        $('#barcodeInput').focus();

        // Optionally, check if this barcode already exists
        checkBarcodeExists(code);
    }

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

    /**
     * Check if barcode already exists in database
     */
    function checkBarcodeExists(barcode) {
        $.ajax({
            url: 'api/check-barcode.php',
            method: 'POST',
            data: { barcode: barcode },
            dataType: 'json',
            success: function(response) {
                if (response.exists) {
                    showNotification(
                        `Warning: Barcode "${barcode}" already exists for item: ${response.itemName}`,
                        'warning'
                    );
                }
            },
            error: function(xhr, status, error) {
                console.warn('Could not check barcode existence:', error);
            }
        });
    }

    /**
     * Show notification message
     */
    function showNotification(message, type = 'info') {
        // Check if modern messagebox is available
        if (typeof MsgBox !== 'undefined') {
            switch(type) {
                case 'success':
                    MsgBox.success(message);
                    break;
                case 'error':
                    MsgBox.error(message);
                    break;
                case 'warning':
                    MsgBox.warning(message);
                    break;
                default:
                    MsgBox.info(message);
            }
            return;
        }

        // Fallback to toast notification
        const toast = $('#toastNotification');
        
        if (toast.length === 0) {
            // Create toast if it doesn't exist
            $('body').append('<div id="toastNotification" class="toast-notification"></div>');
        }

        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 notification animation styles
     */
    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;
                    }
                }

                @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
        initBarcodeScanner();

        // Add visual feedback to scan button
        $('#scanBarcodeBtn').hover(
            function() {
                $(this).find('i').addClass('fa-pulse');
            },
            function() {
                $(this).find('i').removeClass('fa-pulse');
            }
        );

        console.log('Barcode Scanner Integration for Add Item page loaded');
    });

    // Export function for global access
    window.startBarcodeScanner = startScanner;

})();
