// Product Catalog Modal Component
// Барааны лавлагаа харуулах цонх - m_selbarcode ашиглан барааны мэдээлэл үзүүлэх
const { useState, useEffect, useRef } = React;
const MaterialFormModal = window.MaterialFormModal; // Get MaterialFormModal from global scope

// Get api from window object
const api = typeof window !== 'undefined' && window.api ? window.api : null;

function ProductCatalogModal({ 
    isOpen, 
    onClose,
    selectedCompany,
    currentOperator,
    showAlert
}) {
    const [loading, setLoading] = useState(false);
    const [searchBarcode, setSearchBarcode] = useState('');
    const [selectedProduct, setSelectedProduct] = useState(null);
    const [isFormModalOpen, setIsFormModalOpen] = useState(false);
    const [formMaterial, setFormMaterial] = useState(null);
    const [selectedMaterialId, setSelectedMaterialId] = useState(null);
    const [types, setTypes] = useState([]);
    const barcodeInputRef = useRef(null);

    useEffect(() => {
        if (isOpen) {
            setSearchBarcode('');
            setSelectedProduct(null);
            setIsFormModalOpen(false);
            setFormMaterial(null);
            setSelectedMaterialId(null);
            loadTypes();
            
            // Modal нээгдэх үед баркод input-д focus хийж select хийх
            setTimeout(() => {
                if (barcodeInputRef.current) {
                    barcodeInputRef.current.focus();
                    barcodeInputRef.current.select();
                }
            }, 100);
        }
    }, [isOpen]);

    const loadTypes = async () => {
        if (!api) return;
        try {
            const result = await api.getTypes();
            if (result.success && result.data) {
                setTypes(result.data);
            }
        } catch (error) {
            console.error('Error loading types:', error);
        }
    };

    const handleEditProduct = async (m_id) => {
        if (!api || !m_id) return;
        try {
            setLoading(true);
            const result = await api.getMaterialById(m_id);
            if (result.success && result.data) {
                setFormMaterial(result.data);
                setSelectedMaterialId(m_id);
                setIsFormModalOpen(true);
            } else {
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Бараа олдсонгүй!');
                }
            }
        } catch (error) {
            console.error('Error loading material:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Бараа ачаалахад алдаа гарлаа: ' + (error.message || error));
            }
        } finally {
            setLoading(false);
        }
    };

    const handleFormSave = async (materialData) => {
        if (!api) return;
        try {
            setLoading(true);
            const data = {
                ...materialData,
                b_id: selectedCompany?.b_id || null,
                price_low: parseFloat(materialData.price_low) || 0,
                price_big: parseFloat(materialData.price_big) || 0,
                ct_per: parseFloat(materialData.ct_per) || 0,
                pcount: parseFloat(materialData.pcount) || 0,
                barcode: materialData.barcode || null,
                dotcode: materialData.dotcode || null,
                m_type: materialData.m_type || null,
                merchantTin: materialData.merchantTin || null,
                taxType: materialData.taxType || null,
                classificationCode: materialData.classificationCode || null,
                taxProductCode: materialData.taxProductCode || null
            };

            let result;
            let savedMaterialId = selectedMaterialId || null;
            if (selectedMaterialId) {
                result = await api.updateMaterial(selectedMaterialId, data);
            } else {
                result = await api.createMaterial(data);
                savedMaterialId = result?.data?.m_id || result?.m_id || null;
            }

            if (result.success) {
                if (api.setMaterialMatcodes && selectedCompany?.b_id && savedMaterialId) {
                    const matcodeRows = Array.isArray(materialData?.matcodeRows) ? materialData.matcodeRows : [];
                    await api.setMaterialMatcodes(
                        selectedCompany.b_id,
                        savedMaterialId,
                        data.m_name || '',
                        matcodeRows
                    );
                }
                if (showAlert && typeof showAlert === 'function') {
                    showAlert(selectedMaterialId ? 'Бараа амжилттай шинэчлэгдлээ!' : 'Бараа амжилттай нэмэгдлээ!');
                }
                setIsFormModalOpen(false);
                setSelectedMaterialId(null);
                setFormMaterial(null);
            } else {
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Хадгалахад алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
                }
            }
        } catch (error) {
            console.error('Error saving material:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Хадгалахад алдаа гарлаа: ' + (error.message || error));
            }
        } finally {
            setLoading(false);
        }
    };

    const handleFormCancel = () => {
        setIsFormModalOpen(false);
        setSelectedMaterialId(null);
        setFormMaterial(null);
    };

    const handlePrintPriceLabel = () => {
        if (!selectedProduct) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Бараа сонгогдоогүй байна!');
            }
            return;
        }

        // Pricelabel лангуун дээр тавигдах үнэ - price_big эсвэл price_low
        const priceBig = selectedProduct.price_big || 0;
        const priceLow = selectedProduct.price_low || 0;
        const pcount = selectedProduct.pcount || 0;
        const productName = selectedProduct.m_name || selectedProduct.shortname || 'Бүтээгдэхүүн';
        const barcode = selectedProduct.barcode || '';
        
        // price_big байвал pcount болон price_big харуулах
        const showWholesale = priceBig > 0 && pcount > 0;

        // Create price label HTML
        let html = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Үнийн шошго</title>
                <style>
                    @media print {
                        @page {
                            size: 50mm 30mm;
                            margin: 2mm;
                        }
                        body {
                            margin: 0;
                            padding: 0;
                        }
                    }
                    body {
                        font-family: Arial, sans-serif;
                        width: 46mm;
                        padding: 2mm;
                        margin: 0;
                        font-size: 10px;
                    }
                    .label-header {
                        font-weight: bold;
                        font-size: 11px;
                        margin-bottom: 2px;
                        text-align: center;
                        word-wrap: break-word;
                    }
                    .label-price {
                        font-weight: bold;
                        font-size: 24px;
                        text-align: center;
                        margin: 4px 0;
                        color: #000;
                    }
                    .label-wholesale {
                        font-size: 9px;
                        text-align: center;
                        margin: 2px 0;
                        color: #666;
                    }
                    .label-barcode {
                        text-align: center;
                        margin-top: 4px;
                    }
                    .label-barcode-text {
                        font-size: 8px;
                        margin-top: 2px;
                        text-align: center;
                    }
                    .print-actions {
                        position: sticky;
                        top: 0;
                        left: 0;
                        right: 0;
                        padding: 8px;
                        background: #f0f0f0;
                        border-bottom: 1px solid #ccc;
                        text-align: center;
                        z-index: 10;
                    }
                    .print-actions button {
                        padding: 8px 20px;
                        font-size: 14px;
                        cursor: pointer;
                        background: #2563eb;
                        color: #fff;
                        border: none;
                        border-radius: 4px;
                    }
                    .print-actions button:hover {
                        background: #1d4ed8;
                    }
                    @media print {
                        .print-actions {
                            display: none !important;
                        }
                    }
                </style>
            </head>
            <body>
                <div class="print-actions no-print">
                    <button type="button" onclick="window.print()">Хэвлэх</button>
                </div>
                <div class="label-header">${productName.substring(0, 30)}</div>
                ${showWholesale ? `
                    <div class="label-wholesale">${pcount}ш / ${priceBig.toLocaleString('mn-MN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}₮</div>
                    <div class="label-price">${priceLow.toLocaleString('mn-MN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}₮</div>
                ` : `
                    <div class="label-price">${priceLow.toLocaleString('mn-MN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}₮</div>
                `}
                <div class="label-barcode" id="barcode-container"></div>
                <div class="label-barcode-text">${barcode}</div>
                <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
                <script>
                    function runBarcode() {
                        if (typeof JsBarcode !== 'undefined' && '${barcode}') {
                            try {
                                const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                                document.getElementById('barcode-container').appendChild(svg);
                                JsBarcode(svg, '${barcode}', {
                                    width: 1,
                                    height: 30,
                                    fontSize: 10,
                                    margin: 0,
                                    displayValue: false,
                                    format: "CODE128"
                                });
                            } catch (e) {
                                console.error('Barcode error:', e);
                            }
                        }
                    }
                    window.onload = function() { runBarcode(); };
                </script>
            </body>
            </html>
        `;

        // Open print window
        const printWindow = window.open('', '_blank', 'width=360,height=420');
        if (printWindow) {
            printWindow.document.write(html);
            printWindow.document.close();
        } else {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Хэвлэх цонх нээхэд алдаа гарлаа. Pop-up блоклох функцийг идэвхжүүлнэ үү.');
            }
        }
    };

    const handleSearchByBarcode = async () => {
        if (!searchBarcode || !searchBarcode.trim()) {
            return;
        }

        if (!api) {
            return;
        }

        setLoading(true);
        try {
            const b_id = selectedCompany?.b_id || currentOperator?.b_id || 0;
            const result = await api.getProductByBarcode(searchBarcode.trim(), b_id);
            
            if (result.success && result.data) {
                setSelectedProduct(result.data);
                setSearchBarcode('');
                setTimeout(() => {
                    if (barcodeInputRef.current) {
                        barcodeInputRef.current.focus();
                        barcodeInputRef.current.select();
                    }
                }, 0);
            } else {
                setSelectedProduct(null);
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Баркод олдсонгүй: ' + searchBarcode.trim());
                }
            }
        } catch (error) {
            console.error('Error searching product by barcode:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Баркод хайхад алдаа гарлаа: ' + error.message);
            }
            setSelectedProduct(null);
        } finally {
            setLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '900px', maxHeight: '90vh' }}>
                <div className="modal-header">
                    <h2 style={{ fontSize: '16px', margin: 0 }}>Барааны лавлагаа</h2>
                    <button className="modal-close" onClick={onClose} style={{ fontSize: '20px' }}>×</button>
                </div>
                
                <div className="modal-body" style={{ padding: '12px', fontSize: '13px' }}>
                    {/* Баркод хайх */}
                    <div style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                        <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                            <input
                                ref={barcodeInputRef}
                                type="text"
                                className="form-input"
                                value={searchBarcode}
                                onChange={(e) => setSearchBarcode(e.target.value)}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter') {
                                        handleSearchByBarcode();
                                    }
                                }}
                                placeholder="Баркод оруулах..."
                                style={{ flex: 1 }}
                            />
                            <button 
                                className="btn btn-primary" 
                                onClick={handleSearchByBarcode}
                                disabled={loading || !searchBarcode.trim()}
                            >
                                Хайх
                            </button>
                        </div>
                    </div>

                    {/* Баркод-оор олдсон барааны мэдээлэл */}
                    {selectedProduct && (
                        <div style={{ marginBottom: '15px', padding: '15px', backgroundColor: '#e8f5e9', borderRadius: '4px', border: '1px solid #4caf50' }}>
                            <h3 style={{ marginTop: 0, marginBottom: '10px', color: '#2e7d32' }}>Олдсон бараа:</h3>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
                                <div>
                                    <strong>Нэр:</strong> {selectedProduct.m_name || 'N/A'}
                                </div>
                                <div>
                                    <strong>Дотоод код (dotcode):</strong> {selectedProduct.dotcode || 'N/A'}
                                </div>
                                <div>
                                    <strong>Баркод:</strong> {selectedProduct.barcode || 'N/A'}
                                </div>
                                <div>
                                    <strong>m_id:</strong> {selectedProduct.m_id || 'N/A'}
                                </div>
                                <div>
                                    <strong>Үнэ (бага):</strong> {selectedProduct.price_low ? selectedProduct.price_low.toLocaleString('mn-MN') : 'N/A'}
                                </div>
                                <div>
                                    <strong>Бөөний нэгж үнэ (price_big):</strong> {selectedProduct.price_big ? selectedProduct.price_big.toLocaleString('mn-MN') : 'N/A'}
                                </div>
                                <div>
                                    <strong>Төрөл:</strong> {selectedProduct.m_type || 'N/A'}
                                </div>
                                <div>
                                    <strong>Тоо хэмжээ (tcount):</strong> {selectedProduct.tcount !== null && selectedProduct.tcount !== undefined ? selectedProduct.tcount : 'N/A'}
                                </div>
                                <div>
                                    <strong>Бөөний эхлэх тоо (pcount):</strong> {selectedProduct.pcount != null && selectedProduct.pcount !== '' ? selectedProduct.pcount : 'N/A'}
                                </div>
                                <div>
                                    <strong>xn:</strong> {selectedProduct.xn || 'N/A'}
                                </div>
                                <div>
                                    <strong>ct_per:</strong> {selectedProduct.ct_per || 'N/A'}
                                </div>
                            </div>
                            {selectedProduct.m_id && (
                                <div style={{ marginTop: '15px', display: 'flex', gap: '8px' }}>
                                    <button
                                        className="btn btn-secondary"
                                        onClick={() => handleEditProduct(selectedProduct.m_id)}
                                        disabled={loading}
                                        style={{ padding: '8px 16px' }}
                                    >
                                        ✏️ Засах
                                    </button>
                                    <button
                                        className="btn btn-primary"
                                        onClick={handlePrintPriceLabel}
                                        disabled={loading}
                                        style={{ padding: '8px 16px' }}
                                    >
                                        🏷️ Үнийн шошго хэвлэх
                                    </button>
                                </div>
                            )}
                        </div>
                    )}
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={onClose}>
                        Хаах
                    </button>
                </div>
            </div>

            {/* Material Form Modal */}
            {MaterialFormModal && (
                <MaterialFormModal
                    isOpen={isFormModalOpen}
                    onClose={handleFormCancel}
                    onSave={handleFormSave}
                    material={formMaterial}
                    isEditing={!!selectedMaterialId}
                    loading={loading}
                    types={types}
                    onRefreshTypes={loadTypes}
                    api={api}
                    selectedCompany={selectedCompany}
                    showAlert={showAlert}
                />
            )}
        </div>
    );
}

// Export for use in other files
if (typeof window !== 'undefined') {
    window.ProductCatalogModal = ProductCatalogModal;
}

// Export for Node.js/CommonJS
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        ProductCatalogModal
    };
}
