// Material Form Modal Component - Separate modal for adding/editing materials
const { useState, useEffect, useRef } = React;
const MaterialForm = window.MaterialForm; // Get MaterialForm from global scope
const TypeModal = window.TypeModal; // Get TypeModal from global scope
const ClassificationCodeModal = window.ClassificationCodeModal; // Get ClassificationCodeModal from global scope

function MaterialFormModal({
    isOpen,
    onClose,
    onSave,
    material,
    isEditing,
    loading,
    types,
    onRefreshTypes,
    api,
    selectedCompany,
    showAlert,
    showConfirm
}) {
    const [isTypeModalOpen, setIsTypeModalOpen] = useState(false);
    const [isClassificationCodeModalOpen, setIsClassificationCodeModalOpen] = useState(false);
    const mdataLookupTimeoutRef = useRef(null);
    const [matcodeRows, setMatcodeRows] = useState([]);
    const [scanBarcode, setScanBarcode] = useState('');
    const [formMaterial, setFormMaterial] = useState({
        m_name: '',
        shortname: '',
        brand: '',
        price_low: '',
        xn: 'ш',
        barcode: '',
        dotcode: '',
        m_type: '',
        ct_per: '',
        nodiscount: false,
        merchantTin: '',
        taxType: '',
        classificationCode: '',
        taxProductCode: '',
        pcount: '',
        price_big: ''
    });

    const resolveTypeName = (mType) => {
        if (mType === null || mType === undefined || mType === '') {
            return '';
        }
        const mTypeStr = String(mType).trim();
        const matched = (types || []).find((t) => (
            String(t.type_id) === mTypeStr || String(t.type_name) === mTypeStr
        ));
        return matched ? matched.type_name : mTypeStr;
    };

    useEffect(() => {
        if (isOpen && material) {
            setFormMaterial({
                m_name: material.m_name || '',
                shortname: material.shortname || '',
                brand: material.brand || material.m_brand || '',
                price_low: material.price_low || '',
                xn: material.xn || '',
                barcode: material.barcode || '',
                dotcode: material.dotcode || '',
                m_type: resolveTypeName(material.m_type || ''),
                ct_per: material.ct_per || '',
                nodiscount: material.nodiscount ? true : false,
                merchantTin: material.merchantTin || '',
                taxType: material.taxType || '',
                classificationCode: material.classificationCode || '',
                taxProductCode: material.taxProductCode || '',
                pcount: material.pcount || '',
                price_big: material.price_big !== undefined && material.price_big !== null ? material.price_big : ''
            });
        } else if (isOpen && !material) {
            // Reset form for new material
            setFormMaterial({
                m_name: '',
                shortname: '',
                brand: '',
                price_low: '',
                xn: 'ш',
                barcode: '',
                dotcode: '',
                m_type: '',
                ct_per: '',
                nodiscount: false,
                merchantTin: '',
                taxType: '',
                classificationCode: '',
                taxProductCode: '',
                pcount: '',
                price_big: ''
            });
        }
    }, [isOpen, material]);

    useEffect(() => {
        if (!isOpen) return;
        if (!isEditing || !api || !selectedCompany?.b_id || !material?.m_id) {
            setMatcodeRows([]);
            return;
        }
        api.getMaterialMatcodes(selectedCompany.b_id, material.m_id).then((res) => {
            if (res?.success && Array.isArray(res.data)) {
                setMatcodeRows(res.data.map((r) => ({
                    m_id: r.m_id,
                    barcode: r.barcode || '',
                    m_name: r.m_name || material.m_name || ''
                })));
            } else {
                setMatcodeRows([]);
            }
        }).catch((err) => {
            console.error('Failed to load a_matcode list:', err);
            setMatcodeRows([]);
        });
    }, [isOpen, isEditing, api, selectedCompany, material]);

    useEffect(() => {
        if (!isOpen) {
            return;
        }
        setFormMaterial(prev => ({
            ...prev,
            m_type: resolveTypeName(prev.m_type || '')
        }));
    }, [isOpen, types]);

    useEffect(() => {
        if (!isOpen || material || !api || !selectedCompany?.b_id) {
            return;
        }
        
        // Auto-generate dotcode for new materials if empty
        api.getNextDotcode(selectedCompany.b_id).then((result) => {
            if (result && result.success && result.data) {
                setFormMaterial(prev => {
                    if (prev.dotcode && prev.dotcode.toString().trim() !== '') {
                        return prev;
                    }
                    return { ...prev, dotcode: result.data.toString() };
                });
            }
        }).catch((error) => {
            console.error('Error getting next dotcode:', error);
        });
    }, [isOpen, material, api, selectedCompany]);

    useEffect(() => {
        if (!isOpen || material || !api) {
            return;
        }
        
        const rawBarcode = formMaterial.barcode ? formMaterial.barcode.toString().trim() : '';
        const rawDotcode = formMaterial.dotcode ? formMaterial.dotcode.toString().trim() : '';
        const code = rawBarcode || rawDotcode;
        if (!code) {
            return;
        }
        
        if (mdataLookupTimeoutRef.current) {
            clearTimeout(mdataLookupTimeoutRef.current);
        }
        
        mdataLookupTimeoutRef.current = setTimeout(async () => {
            try {
                if (!api.getMdataProductByCode) {
                    return;
                }
                const result = await api.getMdataProductByCode(code);
                if (result && result.success && result.data) {
                    const fetched = result.data;
                    setFormMaterial(prev => ({
                        ...prev,
                        m_name: prev.m_name?.trim() ? prev.m_name : (fetched.m_name || prev.m_name),
                        shortname: prev.shortname?.trim() ? prev.shortname : (fetched.shortname || prev.shortname),
                        brand: prev.brand?.trim() ? prev.brand : (fetched.brand || prev.brand),
                        m_type: prev.m_type?.trim() ? prev.m_type : resolveTypeName(fetched.m_type ? String(fetched.m_type).trim() : prev.m_type),
                        classificationCode: prev.classificationCode?.trim() ? prev.classificationCode : (fetched.classificationCode || prev.classificationCode),
                        taxProductCode: prev.taxProductCode?.trim() ? prev.taxProductCode : (fetched.taxProductCode || prev.taxProductCode)
                    }));
                    if (fetched.m_name) {
                        setTimeout(() => {
                            const priceInput = document.getElementById('materialPriceLowInput');
                            if (priceInput) {
                                priceInput.focus();
                                priceInput.select();
                            }
                        }, 0);
                    }
                }
            } catch (error) {
                console.error('Error fetching product from mdata:', error);
            }
        }, 500);
        
        return () => {
            if (mdataLookupTimeoutRef.current) {
                clearTimeout(mdataLookupTimeoutRef.current);
            }
        };
    }, [isOpen, material, api, formMaterial.barcode, formMaterial.dotcode]);

    const handleSave = () => {
        if (!formMaterial.barcode || formMaterial.barcode.trim() === '') {
            if (formMaterial.dotcode && formMaterial.dotcode.trim() !== '') {
                setFormMaterial(prev => ({
                    ...prev,
                    barcode: prev.dotcode
                }));
            }
        }
        if (!formMaterial.m_name || formMaterial.m_name.trim() === '') {
            if (showAlert) {
                showAlert('Барааны нэр заавал оруулах шаардлагатай!');
            }
            return;
        }
        if (!formMaterial.dotcode || formMaterial.dotcode.trim() === '') {
            if (showAlert) {
                showAlert('Дотоод код (dotcode) заавал оруулах шаардлагатай!');
            }
            return;
        }
        if (onSave) {
            const normalized = {
                ...formMaterial,
                m_type: formMaterial.m_type ? String(formMaterial.m_type).trim() : '',
                matcodeRows: matcodeRows
            };
            onSave(normalized);
        }
    };

    const handleCancel = () => {
        setFormMaterial({
            m_name: '',
            shortname: '',
            brand: '',
            price_low: '',
            xn: 'ш',
            barcode: '',
            dotcode: '',
            m_type: '',
            ct_per: '',
            nodiscount: false,
            merchantTin: '',
            taxType: '',
            classificationCode: '',
            taxProductCode: '',
            pcount: '',
            price_big: ''
        });
        setMatcodeRows([]);
        setScanBarcode('');
        if (onClose) {
            onClose();
        }
    };

    const addMatcodeRow = async (barcodeValue) => {
        const barcode = String(barcodeValue || '').trim();
        if (!barcode) return;
        const exists = matcodeRows.some((r) => String(r?.barcode || '').trim() === barcode);
        if (exists) {
            if (showAlert) showAlert('Энэ баркод жагсаалтанд байна.');
            return;
        }

        // Тухайн байгууллагын хэмжээнд энэ баркод өөр бараанд байгаа эсэхийг шалгана
        try {
            if (api?.getProductByBarcode && selectedCompany?.b_id) {
                const foundRes = await api.getProductByBarcode(barcode, selectedCompany.b_id);
                if (foundRes?.success && foundRes?.data && foundRes.data.m_id) {
                    const foundMId = String(foundRes.data.m_id);
                    const currentMId = String(material?.m_id || '');
                    // Шинэ бараа (currentMId хоосон) үед аль ч олдсон баркодыг хориглоно.
                    // Засварлах үед зөвхөн өөр m_id дээр байвал хориглоно.
                    if (!currentMId || foundMId !== currentMId) {
                        if (showAlert) {
                            showAlert(`Энэ баркод ${foundMId} ID-тай өөр бараанд бүртгэлтэй байна.`);
                        }
                        return;
                    }
                }
            }
        } catch (e) {
            console.warn('Barcode uniqueness check failed:', e?.message || e);
        }

        setMatcodeRows([
            ...matcodeRows,
            {
                m_id: material?.m_id || '',
                barcode,
                m_name: formMaterial.m_name || ''
            }
        ]);
        setScanBarcode('');
    };

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={handleCancel}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '95vw', width: '95vw', maxHeight: '95vh', overflowY: 'auto' }}>
                <div className="modal-header">
                    <h2 style={{ fontSize: '16px', margin: 0 }}>
                        {isEditing ? 'Бараа засах' : 'Шинэ бараа нэмэх'}
                    </h2>
                    <button className="modal-close" onClick={handleCancel} style={{ fontSize: '20px' }}>×</button>
                </div>
                
                <div className="modal-body" style={{ padding: '12px', fontSize: '13px' }}>
                    {MaterialForm && (
                        <MaterialForm
                            material={formMaterial}
                            onChange={setFormMaterial}
                            isEditing={isEditing}
                            loading={loading}
                            types={types}
                            onOpenTypeModal={() => setIsTypeModalOpen(true)}
                            onOpenClassificationCodeModal={() => setIsClassificationCodeModalOpen(true)}
                            showAlert={showAlert}
                        />
                    )}

                    <div className="settings-section" style={{ marginTop: '12px' }}>
                        <h3 className="settings-section-title" style={{ fontSize: '13px' }}>a_matcode баркодын жагсаалт</h3>
                        <div style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
                            <input
                                type="text"
                                className="form-input"
                                value={scanBarcode}
                                onChange={(e) => setScanBarcode(e.target.value)}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        addMatcodeRow(scanBarcode);
                                    }
                                }}
                                placeholder="Баркод уншуулаад Enter дарна..."
                                disabled={loading}
                                style={{ flex: 1 }}
                            />
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => addMatcodeRow(scanBarcode)}
                                disabled={loading || !String(scanBarcode || '').trim()}
                                style={{ padding: '6px 10px', fontSize: '12px' }}
                            >
                                Нэмэх
                            </button>
                        </div>
                        <div style={{ overflowX: 'auto', border: '1px solid #eee', borderRadius: '6px' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>
                                <thead>
                                    <tr style={{ background: '#f5f5f5' }}>
                                        <th style={{ padding: '6px', borderBottom: '1px solid #ddd', textAlign: 'left' }}>Барааны ID</th>
                                        <th style={{ padding: '6px', borderBottom: '1px solid #ddd', textAlign: 'left' }}>Баркод</th>
                                        <th style={{ padding: '6px', borderBottom: '1px solid #ddd', textAlign: 'left' }}>Барааны нэр</th>
                                        <th style={{ padding: '6px', borderBottom: '1px solid #ddd', textAlign: 'center', width: '70px' }}>Үйлдэл</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {matcodeRows.length === 0 && (
                                        <tr>
                                            <td colSpan="4" style={{ padding: '8px', color: '#999' }}>Жагсаалт хоосон</td>
                                        </tr>
                                    )}
                                    {matcodeRows.map((row, idx) => (
                                        <tr key={`${idx}-${row.barcode || ''}`}>
                                            <td style={{ padding: '6px', borderBottom: '1px solid #f0f0f0' }}>
                                                <input
                                                    type="number"
                                                    className="form-input"
                                                    value={row.m_id ?? (material?.m_id || '')}
                                                    onChange={(e) => {
                                                        const next = [...matcodeRows];
                                                        next[idx] = { ...next[idx], m_id: e.target.value };
                                                        setMatcodeRows(next);
                                                    }}
                                                    placeholder={isEditing ? String(material?.m_id || '') : 'm_id'}
                                                    disabled={loading}
                                                    min="1"
                                                />
                                            </td>
                                            <td style={{ padding: '6px', borderBottom: '1px solid #f0f0f0' }}>
                                                <input
                                                    type="text"
                                                    className="form-input"
                                                    value={row.barcode || ''}
                                                    onChange={(e) => {
                                                        const next = [...matcodeRows];
                                                        next[idx] = { ...next[idx], barcode: e.target.value };
                                                        setMatcodeRows(next);
                                                    }}
                                                    placeholder="Баркод"
                                                    disabled={loading}
                                                />
                                            </td>
                                            <td style={{ padding: '6px', borderBottom: '1px solid #f0f0f0' }}>
                                                <input
                                                    type="text"
                                                    className="form-input"
                                                    value={row.m_name || formMaterial.m_name || ''}
                                                    onChange={(e) => {
                                                        const next = [...matcodeRows];
                                                        next[idx] = { ...next[idx], m_name: e.target.value };
                                                        setMatcodeRows(next);
                                                    }}
                                                    placeholder="Нэр"
                                                    disabled={loading}
                                                />
                                            </td>
                                            <td style={{ padding: '6px', borderBottom: '1px solid #f0f0f0', textAlign: 'center' }}>
                                                <button
                                                    type="button"
                                                    className="btn btn-danger"
                                                    onClick={() => setMatcodeRows(matcodeRows.filter((_, i) => i !== idx))}
                                                    disabled={loading}
                                                    style={{ padding: '4px 8px' }}
                                                >
                                                    ✖
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                        <div style={{ marginTop: '8px' }}>
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => setMatcodeRows([
                                    ...matcodeRows,
                                    {
                                        m_id: material?.m_id || '',
                                        barcode: '',
                                        m_name: formMaterial.m_name || ''
                                    }
                                ])}
                                disabled={loading}
                                style={{ padding: '6px 10px', fontSize: '12px' }}
                            >
                                + Баркод нэмэх
                            </button>
                        </div>
                    </div>
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={handleCancel} disabled={loading}>
                        Цуцлах
                    </button>
                    <button className="btn btn-primary" onClick={handleSave} disabled={loading}>
                        {loading ? 'Хадгалж байна...' : (isEditing ? 'Шинэчлэх' : 'Хадгалах')}
                    </button>
                </div>
            </div>
            
            {/* Type Management Modal */}
            {TypeModal && (
                <TypeModal
                    isOpen={isTypeModalOpen}
                    onClose={() => {
                        setIsTypeModalOpen(false);
                        if (onRefreshTypes) {
                            onRefreshTypes(); // Refresh types after closing
                        }
                    }}
                    types={types || []}
                    onRefresh={onRefreshTypes}
                    api={api}
                    showAlert={showAlert}
                    showConfirm={showConfirm}
                />
            )}

            {/* Classification Code Modal */}
            {ClassificationCodeModal && (
                <ClassificationCodeModal
                    isOpen={isClassificationCodeModalOpen}
                    onClose={() => setIsClassificationCodeModalOpen(false)}
                    onSelect={(code, name) => {
                        setFormMaterial({...formMaterial, classificationCode: code});
                        setIsClassificationCodeModalOpen(false);
                    }}
                    selectedCode={formMaterial.classificationCode}
                />
            )}
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.MaterialFormModal = MaterialFormModal;
}

