// Material Modal Component for CRUD operations
const { useState, useEffect, useRef, useCallback } = React;
const MaterialFormModal = window.MaterialFormModal; // Get MaterialFormModal from global scope

function MaterialModal({ 
    isOpen, 
    onClose,
    onSave,
    onRefresh,
    onDelete,
    selectedCompany,
    api,
    showAlert,
    showConfirm
}) {
    const [selectedMaterialId, setSelectedMaterialId] = useState(null);
    const [loading, setLoading] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [types, setTypes] = useState([]);
    const [isTypeModalOpen, setIsTypeModalOpen] = useState(false);
    const [isFormModalOpen, setIsFormModalOpen] = useState(false);
    const [formMaterial, setFormMaterial] = useState(null);
    const [isMaximized, setIsMaximized] = useState(false);
    const [displayedMaterials, setDisplayedMaterials] = useState([]);
    const [hasMore, setHasMore] = useState(true);
    const [currentOffset, setCurrentOffset] = useState(0);
    const [barcodeSearch, setBarcodeSearch] = useState('');
    const scrollContainerRef = useRef(null);
    const searchTimeoutRef = useRef(null);
    const barcodeInputRef = useRef(null);
    
    const resolveTypeName = (mType) => {
        if (mType === null || mType === undefined || mType === '') {
            return '-';
        }
        const mTypeStr = String(mType);
        const matched = types.find((t) => (
            String(t.type_id) === mTypeStr || String(t.type_name) === mTypeStr
        ));
        return matched ? matched.type_name : mTypeStr;
    };
    
    const PAGE_SIZE = 100;

    useEffect(() => {
        if (isOpen) {
            setSearchTerm('');
            setBarcodeSearch('');
            setIsFormModalOpen(false);
            setSelectedMaterialId(null);
            setFormMaterial(null);
            setDisplayedMaterials([]);
            setCurrentOffset(0);
            setHasMore(true);
            setTimeout(() => { if (barcodeInputRef.current) barcodeInputRef.current.focus(); }, 150);
        }
    }, [isOpen]);

    // Эхний хуудсыг жагсаалт нээгдэх даруй татах
    useEffect(() => {
        if (!isOpen || !api || !selectedCompany?.b_id) return;
        setDisplayedMaterials([]);
        setCurrentOffset(0);
        setHasMore(true);
        loadMaterialsPaginated(0, true, '');
    }, [isOpen, api, selectedCompany?.b_id, loadMaterialsPaginated]);

    // Хайлтын үг өөрчлөгдөхөд debounce-аар дахин татах (хоосон биш үед)
    useEffect(() => {
        if (!isOpen || !api || !selectedCompany?.b_id) return;
        if (searchTerm === '') return;

        if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current);
        searchTimeoutRef.current = setTimeout(() => {
            setDisplayedMaterials([]);
            setCurrentOffset(0);
            setHasMore(true);
            loadMaterialsPaginated(0, true, searchTerm);
        }, 500);

        return () => {
            if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current);
        };
    }, [searchTerm, isOpen, api, selectedCompany?.b_id, loadMaterialsPaginated]);

    // Load types when modal opens
    useEffect(() => {
        if (isOpen) {
            loadTypes();
        }
    }, [isOpen]);

    const loadTypes = async () => {
        try {
            const result = await api.getTypes();
            if (result.success && result.data) {
                setTypes(result.data);
            }
        } catch (error) {
            console.error('Error loading types:', error);
        }
    };

    const loadMaterialsPaginated = useCallback(async (offset = 0, reset = false, search = '') => {
        if (!api || !selectedCompany?.b_id) {
            return;
        }

        if (reset) {
            setLoading(true);
        } else {
            setLoadingMore(true);
        }

        try {
            const b_id = selectedCompany.b_id;
            const dep_id = 0; // MaterialModal doesn't use dep_id
            const searchQuery = search !== '' ? search : searchTerm;
            
            // Get materials with pagination
            const result = await api.getProductsPaginated(b_id, dep_id, offset, PAGE_SIZE, searchQuery);
            
            if (result.success && result.data) {
                const newMaterials = result.data;
                
                if (reset) {
                    setDisplayedMaterials(newMaterials);
                } else {
                    setDisplayedMaterials(prev => [...prev, ...newMaterials]);
                }
                
                // Хэрэв 100-аас цөөн ирвэл дахиад байхгүй гэсэн үг
                setHasMore(newMaterials.length === PAGE_SIZE);
                setCurrentOffset(offset + newMaterials.length);
            } else {
                if (reset) {
                    setDisplayedMaterials([]);
                }
                setHasMore(false);
            }
        } catch (error) {
            console.error('Error loading materials:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Барааны жагсаалт ачаалахад алдаа гарлаа: ' + error.message);
            }
            if (reset) {
                setDisplayedMaterials([]);
            }
            setHasMore(false);
        } finally {
            setLoading(false);
            setLoadingMore(false);
        }
    }, [api, selectedCompany, showAlert]);

    // Infinite scroll handler
    const handleScroll = useCallback((e) => {
        const container = e.target;
        const scrollTop = container.scrollTop;
        const scrollHeight = container.scrollHeight;
        const clientHeight = container.clientHeight;

        // Scroll дээр 100px үлдэхэд дараагийн багц ачаална
        if (scrollHeight - scrollTop - clientHeight < 100 && hasMore && !loadingMore && !loading) {
            loadMaterialsPaginated(currentOffset, false);
        }
    }, [hasMore, loadingMore, loading, currentOffset, loadMaterialsPaginated]);

    const handleSearchByBarcode = async () => {
        const code = (barcodeSearch || '').trim();
        if (!code || !api || !selectedCompany?.b_id) return;
        setLoading(true);
        try {
            const result = await api.getProductByBarcode(code, selectedCompany.b_id);
            if (result.success && result.data && result.data.m_id) {
                setBarcodeSearch('');
                setFormMaterial(result.data);
                setSelectedMaterialId(result.data.m_id);
                setIsFormModalOpen(true);
            } else {
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Баркод олдсонгүй: ' + code);
                }
            }
        } catch (error) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Баркод хайхад алдаа: ' + (error.message || error));
            }
        } finally {
            setLoading(false);
        }
    };

    const handleEdit = async (m_id) => {
        try {
            setLoading(true);
            const result = await api.getMaterialById(m_id);
            if (result.success && result.data) {
                setFormMaterial(result.data);
                setSelectedMaterialId(m_id);
                setIsFormModalOpen(true);
            } else {
                showAlert('Бараа олдсонгүй!');
            }
        } catch (error) {
            console.error('Error loading material:', error);
            showAlert('Бараа ачаалахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (m_id) => {
        const confirmMessage = 'Энэ барааг устгахдаа итгэлтэй байна уу?';
        if (showConfirm && typeof showConfirm === 'function') {
            showConfirm(confirmMessage, () => {
                // Continue with delete
                performDelete(m_id);
            });
            return;
        }
        // Fallback - if no showConfirm, don't delete
        return;
    };
    
    const performDelete = async (m_id) => {
        
        try {
            setLoading(true);
            const result = await api.deleteMaterial(m_id, selectedCompany?.b_id || null);
            if (result.success) {
                showAlert('Бараа амжилттай устгагдлаа!');
                // Refresh materials list
                setDisplayedMaterials([]);
                setCurrentOffset(0);
                setHasMore(true);
                loadMaterialsPaginated(0, true);
                if (selectedMaterialId === m_id) {
                    setSelectedMaterialId(null);
                }
            } else {
                showAlert('Бараа устгахад алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
            }
        } catch (error) {
            console.error('Error deleting material:', error);
            showAlert('Бараа устгахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleFormSave = async (materialData) => {
        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
                    );
                }
                showAlert(selectedMaterialId ? 'Бараа амжилттай шинэчлэгдлээ!' : 'Бараа амжилттай нэмэгдлээ!');
                // Refresh materials list
                setDisplayedMaterials([]);
                setCurrentOffset(0);
                setHasMore(true);
                loadMaterialsPaginated(0, true);
                setIsFormModalOpen(false);
                setSelectedMaterialId(null);
                setFormMaterial(null);
                if (onSave) {
                    onSave();
                }
            } else {
                showAlert('Хадгалахад алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
            }
        } catch (error) {
            console.error('Error saving material:', error);
            showAlert('Хадгалахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleNewMaterial = () => {
        setFormMaterial(null);
        setSelectedMaterialId(null);
        setIsFormModalOpen(true);
    };

    const handleFormCancel = () => {
        setIsFormModalOpen(false);
        setSelectedMaterialId(null);
        setFormMaterial(null);
    };

    // Use displayedMaterials instead of filteredMaterials
    const filteredMaterials = displayedMaterials;

    if (!isOpen) return null;

    const toggleMaximize = () => {
        setIsMaximized(!isMaximized);
    };

    const modalStyle = isMaximized 
        ? { 
            maxWidth: '100vw', 
            width: '100vw', 
            maxHeight: '100vh', 
            height: '100vh',
            margin: 0,
            borderRadius: 0,
            overflowY: 'auto' 
        }
        : { 
            maxWidth: '1200px', 
            width: '95vw', 
            maxHeight: '85vh', 
            overflowY: 'auto' 
        };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={modalStyle}>
                <div className="modal-header">
                    <h2 style={{ fontSize: '16px', margin: 0 }}>Барааны мэдээлэл (a_material)</h2>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                        <button 
                            className="modal-close" 
                            onClick={toggleMaximize} 
                            style={{ fontSize: '18px', padding: '4px 8px', background: 'transparent', border: 'none', cursor: 'pointer' }}
                            title={isMaximized ? 'Жижиглэх' : 'Томруулах'}
                        >
                            {isMaximized ? '🗗' : '🗖'}
                        </button>
                        <button className="modal-close" onClick={onClose} style={{ fontSize: '20px' }}>×</button>
                    </div>
                </div>
                
                <div className="modal-body" style={{ padding: '15px', fontSize: '14px' }}>
                    {/* Лавлагаа шиг: баркодоор хайх */}
                    <div style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
                        <div style={{ display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
                            <input
                                ref={barcodeInputRef}
                                type="text"
                                className="form-input"
                                value={barcodeSearch}
                                onChange={(e) => setBarcodeSearch(e.target.value)}
                                onKeyPress={(e) => { if (e.key === 'Enter') handleSearchByBarcode(); }}
                                placeholder="Баркод оруулаад Enter эсвэл Хайх дарна..."
                                style={{ flex: '1', minWidth: '200px', fontSize: '14px', padding: '8px 12px' }}
                            />
                            <button
                                className="btn btn-primary"
                                onClick={handleSearchByBarcode}
                                disabled={loading || !barcodeSearch.trim()}
                                style={{ padding: '8px 16px' }}
                            >
                                Хайх
                            </button>
                            <button
                                className="btn btn-secondary"
                                onClick={() => { setBarcodeSearch(''); if (barcodeInputRef.current) barcodeInputRef.current.focus(); }}
                                style={{ padding: '8px 12px' }}
                            >
                                Цэвэрлэх
                            </button>
                        </div>
                    </div>
                    {/* Material List */}
                    <div style={{ marginBottom: '15px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                            <h3 style={{ margin: 0, fontSize: '18px', fontWeight: 'bold' }}>Барааны жагсаалт</h3>
                            <button
                                className="btn btn-primary"
                                onClick={handleNewMaterial}
                                style={{ padding: '8px 16px', fontSize: '14px' }}
                            >
                                + Шинэ бараа
                            </button>
                        </div>
                        <input
                            type="text"
                            className="form-input"
                            placeholder="Текстээр хайх (нэр, баркод, төрөл)..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            style={{ marginBottom: '10px', width: '100%', fontSize: '14px', padding: '8px 12px' }}
                        />
                        <div 
                            ref={scrollContainerRef}
                            onScroll={handleScroll}
                            style={{ maxHeight: '70vh', overflowY: 'auto', border: '1px solid #ddd', borderRadius: '6px' }}
                        >
                            {loading && displayedMaterials.length === 0 ? (
                                <div style={{ textAlign: 'center', padding: '20px' }}>
                                    Ачааллаж байна...
                                </div>
                            ) : (
                            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>
                                <thead>
                                    <tr style={{ background: '#f5f5f5', position: 'sticky', top: 0 }}>
                                        <th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Нэр</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Дотоод код</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Жижиглэн</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Бөөний үнэ</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Хэмж. нэгж</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Баркод</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }}>Төрөл</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold' }} title="Бөөний эхлэх тоо (pcount)">Бөөний тоо</th>
                                        <th style={{ padding: '6px 8px', textAlign: 'center', borderBottom: '2px solid #ddd', fontSize: '12px', fontWeight: 'bold', width: '140px', minWidth: '140px' }}>Үйлдэл</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {filteredMaterials.length === 0 ? (
                                        <tr>
                                            <td colSpan="9" style={{ padding: '15px', textAlign: 'center', color: '#999', fontSize: '12px' }}>
                                                Бараа олдсонгүй
                                            </td>
                                        </tr>
                                    ) : (
                                        filteredMaterials.map((m) => (
                                            <tr key={m.m_id} style={{ borderBottom: '1px solid #eee' }}>
                                                <td style={{ padding: '6px 8px', fontSize: '12px' }}>{m.m_name || '-'}</td>
                                                <td style={{ padding: '6px 8px', fontSize: '12px' }}>{m.dotcode || '-'}</td>
                                                <td style={{ padding: '6px 8px', textAlign: 'right', fontSize: '12px' }}>{m.price_low || 0}</td>
                                                <td style={{ padding: '6px 8px', textAlign: 'right', fontSize: '12px' }}>{m.price_big != null && m.price_big !== '' ? m.price_big : 0}</td>
                                                <td style={{ padding: '6px 8px', fontSize: '12px' }}>{m.xn || '-'}</td>
                                                <td style={{ padding: '6px 8px', fontSize: '12px' }}>{m.barcode || '-'}</td>
                                                <td style={{ padding: '6px 8px', fontSize: '12px' }}>{resolveTypeName(m.m_type)}</td>
                                                <td style={{ padding: '6px 8px', textAlign: 'right', fontSize: '12px' }}>{m.pcount || 0}</td>
                                                <td style={{ padding: '6px 8px', textAlign: 'center', width: '140px', minWidth: '140px' }}>
                                                    <button
                                                        className="btn btn-secondary"
                                                        onClick={() => handleEdit(m.m_id)}
                                                        title="Засах"
                                                        style={{ padding: '4px 8px', fontSize: '12px', marginRight: '4px', lineHeight: '1' }}
                                                        disabled={loading}
                                                    >
                                                        ✏️ Засах
                                                    </button>
                                                    <button
                                                        className="btn btn-danger"
                                                        onClick={() => handleDelete(m.m_id)}
                                                        title="Устгах"
                                                        style={{ padding: '4px 8px', fontSize: '12px', lineHeight: '1' }}
                                                        disabled={loading}
                                                    >
                                                        🗑️ Устгах
                                                    </button>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                            )}
                            {loadingMore && (
                                <div style={{ textAlign: 'center', padding: '10px', color: '#666' }}>
                                    Ачааллаж байна...
                                </div>
                            )}
                        </div>
                        <div style={{ marginTop: '10px', fontSize: '11px', color: '#666' }}>
                            Нийт: {displayedMaterials.length} бараа {hasMore ? '(дахиад байна...)' : '(бүгд)'}
                        </div>
                    </div>

                </div>
            </div>

            {/* Type Management Modal */}
            <TypeModal
                isOpen={isTypeModalOpen}
                onClose={() => {
                    setIsTypeModalOpen(false);
                    loadTypes(); // Refresh types after closing
                }}
                types={types}
                onRefresh={loadTypes}
                api={api}
                showAlert={showAlert}
                showConfirm={showConfirm}
            />

            {/* 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}
                    showConfirm={showConfirm}
                />
            )}
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.MaterialModal = MaterialModal;
}

