{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="container-fluid mt-4 mb-5 no-print">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="h4 mb-0"><i class="bi bi-upc-scan me-2"></i>Barcode Label Printing</h2>
        <button id="printQueueBtn" class="btn btn-primary">
            <i class="bi bi-printer me-2"></i>Print Label Queue
        </button>
    </div>

    <div class="row">
        <!-- Product Selection -->
        <div class="col-md-5">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white py-3">
                    <h5 class="card-title mb-0">1. Select Products</h5>
                </div>
                <div class="card-body">
                    <div class="input-group mb-3">
                        <span class="input-group-text bg-light border-end-0"><i class="bi bi-search"></i></span>
                        <input type="text" id="productSearch" class="form-control border-start-0 ps-0" placeholder="Search by name or SKU...">
                    </div>
                    <div class="table-responsive" style="max-height: 500px;">
                        <table class="table table-hover align-middle" id="productTable">
                            <thead class="table-light sticky-top">
                                <tr>
                                    <th>Product</th>
                                    <th>SKU</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for product in products %}
                                <tr class="product-row" data-name="{{ product.name_en }}" data-name-ar="{{ product.name_ar }}" data-sku="{{ product.sku }}">
                                    <td>
                                        <div class="fw-bold">{{ product.name_en }}</div>
                                        <small class="text-muted">{{ product.name_ar }}</small>
                                    </td>
                                    <td><code>{{ product.sku }}</code></td>
                                    <td>
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-sm btn-outline-primary add-to-queue-btn" 
                                                    data-id="{{ product.id }}" 
                                                    data-name="{{ product.name_en }}" data-name-ar="{{ product.name_ar }}" 
                                                    data-sku="{{ product.sku }}"
                                                    data-price="{{ product.price }}"
                                                    title="Add to queue">
                                                <i class="bi bi-plus"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-success direct-print-btn"
                                                    data-id="{{ product.id }}" 
                                                    data-name="{{ product.name_en }}" data-name-ar="{{ product.name_ar }}" 
                                                    data-sku="{{ product.sku }}"
                                                    data-price="{{ product.price }}"
                                                    title="Direct Print Single Label">
                                                <i class="bi bi-printer"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Label Queue & Settings -->
        <div class="col-md-7">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white py-3">
                    <h5 class="card-title mb-0">2. Label Queue & Settings</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Label Size / Type</label>
                            <select id="labelType" class="form-select">
                                <option value="standard">Standard Sticker (50mm x 25mm)</option>
                                <option value="small">Small Sticker (38mm x 25mm)</option>
                                <option value="a4-24">A4 Sheet (3x8 = 24 labels)</option>
                                <option value="a4-40">A4 Sheet (4x10 = 40 labels)</option>
                                <option value="l7651" selected>A4 Avery L7651 (5x13 = 65 labels)</option>
                                <option value="l7656">A4 Avery L7656 (4x21 = 84 labels)</option>
                                <option value="l7156">A4 Avery L7156 (3x7 = 21 labels)</option>
                                <option value="price-tag">Jewelry / Price Tag (Small)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Include Fields</label>
                            <div class="d-flex gap-3 mt-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="showName" checked>
                                    <label class="form-check-label" for="showName">Name</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="showPrice" checked>
                                    <label class="form-check-label" for="showPrice">Price</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="showSKU" checked>
                                    <label class="form-check-label" for="showSKU">SKU Text</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Product</th>
                                    <th style="width: 120px;">Qty of Labels</th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody id="labelQueue">
                                <!-- Dynamic content -->
                            </tbody>
                        </table>
                        <div id="emptyQueue" class="text-center py-4 text-muted">
                            <i class="bi bi-cart-x display-4 d-block mb-2"></i>
                            Queue is empty. Select products to start.
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Live Preview -->
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">3. Live Preview (Single Label)</h5>
                    <button type="button" class="btn btn-sm btn-success" id="printPreviewBtn">
                        <i class="bi bi-printer me-1"></i>Print This Label
                    </button>
                </div>
                <div class="card-body text-center bg-light p-5">
                    <div id="previewContainer" class="d-inline-block bg-white shadow-sm p-3 border">
                        <div id="previewLabelContent">
                            <div class="preview-name fw-bold small mb-1">Product Name</div>
                            <svg id="previewBarcode"></svg>
                            <div class="preview-footer d-flex justify-content-between mt-1 small">
                                <span class="preview-sku">SKU12345</span>
                                <span class="preview-price fw-bold">OMR 0.000</span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-3 text-muted small">
                        Note: This is a preview of the layout. Actual print layout depends on settings above.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- PRINT VIEW (Hidden by default) -->
<div id="printArea" class="print-only">
    <!-- Generated labels will go here -->
</div>

<style>
    /* Print Styles */
    @media screen {
        .print-only { 
            display: none !important;
        }
    }
    @media print {
        /* Force hiding of everything except printArea */
        body > *:not(#printArea) {
            display: none !important;
        }

        /* Ensure printArea is visible */
        #printArea {
            display: block !important;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: auto;
            overflow: visible !important;
            z-index: 9999;
            background: white;
            text-align: left !important;
        }

        body { 
            margin: 0; 
            padding: 0; 
            background: white !important; 
            -webkit-print-color-adjust: exact;
            text-align: left !important;
            display: block !important;
        }
        
        @page { 
            size: A4; 
            margin: 0; 
        }

        /* Direct Print Mode Overrides */
        body.direct-print-mode @page {
            size: auto;
            margin: 0;
        }
        
        .label-sheet {
            position: relative;
            width: 210mm !important; /* Force A4 width */
            min-height: 297mm;
            margin: 0 !important; /* Strict Left align */
            padding: 0;
            background: white;
            page-break-after: always;
            box-sizing: border-box;
            
            /* Use Flexbox for Grid Layout - More reliable for print */
            display: flex !important;
            flex-wrap: wrap !important;
            justify-content: flex-start !important;
            align-items: flex-start !important;
        }
        
        /* Direct print container override */
        body.direct-print-mode .label-sheet {
            width: auto !important;
            min-height: auto;
            page-break-after: auto;
            display: block !important;
        }

        .label-item {
            box-sizing: border-box;
            text-align: center;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            /* REMOVED width: 100% to prevent full-width expansion */
            page-break-inside: avoid;
            float: left; /* Fallback */
        }

        /* --- SHEET CONFIGURATIONS (Flexbox + Explicit Dimensions) --- */
        
        /* Avery L7651 (5x13 = 65) */
        .sheet-l7651 {
            padding: 10.7mm 9.75mm !important;
        }
        .label-l7651 { 
            width: 38.1mm !important;
            height: 21.2mm !important;
            padding: 1mm;
            border: none; /* Debug: add border: 1px solid #eee if needed */
        }

        /* Avery L7656 (4x21 = 84) */
        .sheet-l7656 {
            padding: 31.95mm 13mm !important;
        }
        .label-l7656 { 
            width: 46mm !important;
            height: 11.1mm !important;
            padding: 0.5mm;
        }
        .label-l7656 .inner-flex {
             display: flex; flex-direction: row; justify-content: space-around; align-items: center; height: 100%; width: 100%;
        }
        .label-l7656 svg { height: 8mm !important; width: auto; }
        .label-l7656 .label-text { font-size: 5pt !important; width: auto !important; margin: 0 2px; }

        /* Avery L7156 (3x7 = 21) */
        .sheet-l7156 {
            padding: 15.15mm 9.75mm !important;
        }
        .label-l7156 { 
            width: 63.5mm !important;
            height: 38.1mm !important;
            padding: 2mm;
        }

        /* A4 24 (3x8) */
        .sheet-a4-24 {
            padding: 12.9mm 9.75mm !important;
        }
        .label-a4-24 {
            width: 63.5mm !important;
            height: 33.9mm !important;
            padding: 2mm;
        }

        /* A4 40 (4x10) */
        .sheet-a4-40 {
            padding: 21.5mm 8mm !important;
        }
        .label-a4-40 {
            width: 48.5mm !important;
            height: 25.4mm !important;
            padding: 1mm;
        }

        /* Standard / Small / Price Tag */
        .sheet-standard, .sheet-small {
            padding: 5mm !important;
            gap: 2mm !important;
        }
        .label-standard { width: 50mm !important; height: 25mm !important; border: 1px dotted #ccc; }
        .label-small { width: 38mm !important; height: 25mm !important; border: 1px dotted #ccc; }
        .label-price-tag { width: 25mm !important; height: 15mm !important; border: 1px dotted #ccc; }

        /* Inner Content Styling */
        .label-item svg {
            max-width: 95%;
            height: auto;
            display: block;
            margin: 0 auto;
        }
        
        .label-text {
            font-family: 'Cairo', Arial, sans-serif;
            font-size: 7pt;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            line-height: 1.2;
            display: block;
        }
        .label-price {
            font-size: 9pt;
            font-weight: bold;
        }
        
        .d-flex-print { display: flex; justify-content: space-between; width: 100%; }
    }

    #previewBarcode {
        max-width: 100%;
        height: auto;
    }
</style>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const queue = [];
    const labelQueueBody = document.getElementById('labelQueue');
    const emptyQueue = document.getElementById('emptyQueue');
    const printArea = document.getElementById('printArea');
    let lastAddedProduct = null;

    // Move printArea to body safely
    if (printArea && printArea.parentElement !== document.body) {
        document.body.appendChild(printArea);
    }

    // Check for JsBarcode
    if (typeof JsBarcode === 'undefined') {
        console.error("JsBarcode library not loaded!");
        alert("Barcode library failed to load. Please check your internet connection.");
    }

    // --- EVENT DELEGATION FOR PRODUCT TABLE ---
    const productTable = document.getElementById('productTable');
    if (productTable) {
        productTable.addEventListener('click', function(e) {
            // Handle "Add to Queue"
            const addBtn = e.target.closest('.add-to-queue-btn');
            if (addBtn) {
                e.preventDefault();
                addToQueue(addBtn);
                return;
            }

            // Handle "Direct Print"
            const directBtn = e.target.closest('.direct-print-btn');
            if (directBtn) {
                e.preventDefault();
                directPrintFromRow(directBtn);
                return;
            }
        });
    }

    // --- ADD TO QUEUE LOGIC ---
    function addToQueue(btn) {
        try {
            const product = {
                id: btn.dataset.id,
                name: btn.dataset.name, 
                nameAr: btn.dataset.nameAr,
                sku: btn.dataset.sku,
                price: btn.dataset.price,
                qty: 1
            };
            lastAddedProduct = product;
            
            const existing = queue.find(p => p.id === product.id);
            if (existing) {
                existing.qty++;
            } else {
                queue.push(product);
            }
            renderQueue();
            updatePreview();
        } catch (err) {
            console.error("Error adding to queue:", err);
            alert("An error occurred while adding the item.");
        }
    }

    // --- RENDER QUEUE ---
    function renderQueue() {
        if (queue.length === 0) {
            labelQueueBody.innerHTML = '';
            emptyQueue.classList.remove('d-none');
            printArea.innerHTML = ''; 
            return;
        }
        emptyQueue.classList.add('d-none');
        labelQueueBody.innerHTML = queue.map((p, index) => `
            <tr>
                <td>
                    <div class="fw-bold small">${p.nameAr ? p.nameAr + " | " : ""}${p.name}</div>
                    <code class="text-muted small">${p.sku}</code>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm qty-input" 
                           value="${p.qty}" min="1" data-index="${index}">
                </td>
                <td class="text-end">
                    <button type="button" class="btn btn-sm btn-link text-danger remove-btn" data-index="${index}">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            </tr>
        `).join('');
        
        // Re-attach listeners for dynamic queue items
        document.querySelectorAll('.qty-input').forEach(input => {
            input.addEventListener('change', function() {
                const idx = parseInt(this.dataset.index);
                const val = parseInt(this.value);
                if (val > 0) {
                    queue[idx].qty = val;
                    preparePrint();
                }
            });
        });
        
        document.querySelectorAll('.remove-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const idx = parseInt(this.dataset.index);
                queue.splice(idx, 1);
                renderQueue();
                updatePreview();
            });
        });

        // Pre-render print area
        preparePrint();
    }

    // --- PRINT HANDLERS ---
    const printQueueBtn = document.getElementById('printQueueBtn');
    if (printQueueBtn) {
        printQueueBtn.addEventListener('click', handlePrintQueue);
    }

    function handlePrintQueue() {
        if (queue.length === 0) return;
        preparePrint(); 
        setTimeout(() => {
            window.print();
        }, 500);
    }
    
    const printPreviewBtn = document.getElementById('printPreviewBtn');
    if (printPreviewBtn) {
        printPreviewBtn.addEventListener('click', printSingleFromPreview);
    }

    // Product Search
    const searchInput = document.getElementById('productSearch');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase();
            document.querySelectorAll('.product-row').forEach(row => {
                const name = row.dataset.name.toLowerCase();
                const nameAr = row.dataset.nameAr ? row.dataset.nameAr.toLowerCase() : '';
                const sku = row.dataset.sku.toLowerCase();
                if (name.includes(query) || nameAr.includes(query) || sku.includes(query)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    }

    // --- PREVIEW LOGIC ---
    function updatePreview() {
        let product = null;
        if (queue.length > 0) {
            product = queue[queue.length - 1];
        } else if (lastAddedProduct) {
            product = lastAddedProduct;
        }
        
        if (!product) return;
        
        const previewName = document.querySelector('.preview-name');
        const previewSku = document.querySelector('.preview-sku');
        const previewPrice = document.querySelector('.preview-price');
        
        if (previewName) previewName.innerHTML = (product.nameAr ? `<div class='text-end'>${product.nameAr}</div>` : '') + `<div>${product.name}</div>`;
        if (previewSku) previewSku.innerText = product.sku;
        if (previewPrice) previewPrice.innerText = 'OMR ' + parseFloat(product.price).toFixed(3);
        
        try {
            if (typeof JsBarcode !== 'undefined') {
                JsBarcode("#previewBarcode", product.sku, {
                    format: "CODE128", width: 2, height: 40, displayValue: false, margin: 0
                });
            }
        } catch(e) {}

        const showName = document.getElementById('showName').checked;
        const showPrice = document.getElementById('showPrice').checked;
        const showSKU = document.getElementById('showSKU').checked;
        
        if (previewName) previewName.style.display = showName ? '' : 'none';
        if (previewPrice) previewPrice.style.display = showPrice ? '' : 'none';
        if (previewSku) previewSku.style.display = showSKU ? '' : 'none';
    }

    // --- DIRECT PRINT ---
    function directPrintFromRow(btn) {
        const product = {
            id: btn.dataset.id,
            name: btn.dataset.name, nameAr: btn.dataset.nameAr,
            sku: btn.dataset.sku,
            price: btn.dataset.price,
            qty: 1
        };
        performDirectPrint(product);
    }

    function printSingleFromPreview() {
        let product = null;
        if (queue.length > 0) {
            product = queue[queue.length - 1];
        } else if (lastAddedProduct) {
            product = lastAddedProduct;
        }
        if (product) performDirectPrint(product);
    }

    function performDirectPrint(product) {
        document.body.classList.add('direct-print-mode');
        printArea.innerHTML = '';
        const labelType = document.getElementById('labelType').value;
        const showName = document.getElementById('showName').checked;
        const showPrice = document.getElementById('showPrice').checked;
        const showSKU = document.getElementById('showSKU').checked;

        const sheet = document.createElement('div');
        sheet.className = 'label-sheet';
        sheet.style.height = 'auto';
        sheet.style.width = 'auto';
        sheet.style.display = 'block';

        const label = document.createElement('div');
        label.className = `label-item label-${labelType}`;
        
        let content = '';
        if (labelType === 'l7656') {
             content = `<div class="inner-flex">`;
             if (showName) content += `<div class="label-text" style="max-width: 40px">${product.nameAr ? product.nameAr + " " : ""}${product.name}</div>`;
             content += `<svg class="barcode-svg-direct"></svg>`;
             if (showPrice) content += `<div class="label-text label-price">${parseFloat(product.price).toFixed(3)}</div>`;
             content += `</div>`;
        } else {
            if (showName) { if (product.nameAr) content += `<div class="label-text">${product.nameAr}</div>`; content += `<div class="label-text">${product.name}</div>`; }
            content += `<svg class="barcode-svg-direct"></svg>`;
            if (showSKU || showPrice) {
                content += `<div class="label-text d-flex-print">`;
                if (showSKU) content += `<span>${product.sku}</span>`;
                if (showPrice) content += `<span class="label-price">OMR ${parseFloat(product.price).toFixed(3)}</span>`;
                content += `</div>`;
            }
        }

        label.innerHTML = content;
        sheet.appendChild(label);
        printArea.appendChild(sheet);

        let bWidth = 1.5;
        let bHeight = 30;
        if (labelType === 'l7651') { bWidth = 1.0; bHeight = 20; }
        else if (labelType === 'l7656') { bWidth = 0.8; bHeight = 8; }
        else if (labelType === 'a4-40') { bWidth = 1.2; bHeight = 25; }
        else if (labelType === 'price-tag') { bWidth = 1.0; bHeight = 15; }

        const svgEl = label.querySelector('.barcode-svg-direct');
        if (svgEl && typeof JsBarcode !== 'undefined') {
             try {
                JsBarcode(svgEl, product.sku, {
                    format: "CODE128", width: bWidth, height: bHeight, displayValue: false, margin: 0
                });
             } catch(e){}
        }

        setTimeout(() => {
            window.print();
            document.body.classList.remove('direct-print-mode');
            preparePrint(); 
        }, 500);
    }

    // --- PREPARE PRINT (Full Queue) ---
    function preparePrint() {
        // Ensure we are not in direct print mode
        document.body.classList.remove('direct-print-mode');
        
        printArea.innerHTML = '';
        const labelType = document.getElementById('labelType').value;
        const showName = document.getElementById('showName').checked;
        const showPrice = document.getElementById('showPrice').checked;
        const showSKU = document.getElementById('showSKU').checked;

        let labelsPerSheet = 999999;
        if (labelType === 'a4-24') labelsPerSheet = 24;
        else if (labelType === 'a4-40') labelsPerSheet = 40;
        else if (labelType === 'l7651') labelsPerSheet = 65;
        else if (labelType === 'l7656') labelsPerSheet = 84;
        else if (labelType === 'l7156') labelsPerSheet = 21;

        const allLabels = [];
        queue.forEach(p => {
            for (let i = 0; i < p.qty; i++) {
                allLabels.push({ ...p });
            }
        });

        if (allLabels.length === 0) return;

        for (let s = 0; s < allLabels.length; s += labelsPerSheet) {
            const sheetLabels = allLabels.slice(s, s + labelsPerSheet);
            const sheet = document.createElement('div');
            
            sheet.classList.add('label-sheet');
            sheet.classList.add('sheet-' + labelType); 

            printArea.appendChild(sheet);

            sheetLabels.forEach((p, idx) => {
                const label = document.createElement('div');
                label.className = `label-item label-${labelType}`;
                
                // Construct inner HTML
                let content = '';
                if (labelType === 'l7656') {
                    content = `<div class="inner-flex">`;
                    if (showName) content += `<div class="label-text" style="max-width: 40px">${p.nameAr ? p.nameAr + " " : ""}${p.name}</div>`;
                    content += `<svg class="barcode-item"></svg>`;
                    if (showPrice) content += `<div class="label-text label-price">${parseFloat(p.price).toFixed(3)}</div>`;
                    content += `</div>`;
                } else {
                    if (showName) { 
                        if (p.nameAr) content += `<div class="label-text">${p.nameAr}</div>`; 
                        content += `<div class="label-text">${p.name}</div>`; 
                    }
                    content += `<svg class="barcode-item"></svg>`;
                    if (showSKU || showPrice) {
                        content += `<div class="label-text d-flex-print">`;
                        if (showSKU) content += `<span>${p.sku}</span>`;
                        if (showPrice) content += `<span class="label-price">${parseFloat(p.price).toFixed(3)}</span>`;
                        content += `</div>`;
                    }
                }

                label.innerHTML = content;
                sheet.appendChild(label);

                // Render barcode immediately (synchronously)
                const svgEl = label.querySelector('.barcode-item');
                if (svgEl && typeof JsBarcode !== 'undefined') {
                    let bWidth = 1.5;
                    let bHeight = 30;
                    if (labelType === 'l7651') { bWidth = 1.0; bHeight = 18; }
                    else if (labelType === 'l7656') { bWidth = 0.8; bHeight = 8; }
                    else if (labelType === 'a4-40') { bWidth = 1.1; bHeight = 22; }
                    else if (labelType === 'price-tag') { bWidth = 1.0; bHeight = 12; }

                    try {
                        JsBarcode(svgEl, p.sku, {
                            format: "CODE128", width: bWidth, height: bHeight, displayValue: false, margin: 0
                        });
                    } catch(e) { console.error(e); }
                }
            });
        }
    }

    // --- SETUP LISTENERS ---
    document.getElementById('labelType').addEventListener('change', () => preparePrint());
    document.getElementById('showName').addEventListener('change', () => { updatePreview(); preparePrint(); });
    document.getElementById('showPrice').addEventListener('change', () => { updatePreview(); preparePrint(); });
    document.getElementById('showSKU').addEventListener('change', () => { updatePreview(); preparePrint(); });

    updatePreview();
});
</script>
{% endblock %}