// Classification Code Modal Component - Grid structure for classification codes from tax system
const { useState, useEffect } = React;

function ClassificationCodeModal({ 
    isOpen, 
    onClose,
    onSelect,
    selectedCode = null
}) {
    const [loading, setLoading] = useState(false);
    const [gridData, setGridData] = useState([]); // Grid data: [{code, name, p1, p2, p3, p4, p5, p6}]
    const [searchTerm, setSearchTerm] = useState('');
    const [currentParams, setCurrentParams] = useState({ p1: '', p2: '', p3: '', p4: '', p5: '', p6: '' }); // Current query parameters

    useEffect(() => {
        if (isOpen) {
            loadRootClassificationCodes();
            setSearchTerm('');
            setCurrentParams({ p1: '', p2: '', p3: '', p4: '', p5: '', p6: '' });
        }
    }, [isOpen]);

    // Эхлээд root level ангилалын кодыг татах (parameter-гүйгээр)
    const loadRootClassificationCodes = async () => {
        setLoading(true);
        try {
            // API endpoint: /api/info/check/barcode/v2 (parameter-гүйгээр)
            const apiUrl = 'https://api.ebarimt.mn/api/info/check/barcode/v2';
            
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                
                // Response формат: [["0", "Нэр"], ["1", "Нэр"], ...]
                let codes = [];
                if (data && Array.isArray(data)) {
                    codes = data;
                } else if (data && data.data && Array.isArray(data.data)) {
                    codes = data.data;
                } else if (data && data.status === 200 && data.data && Array.isArray(data.data)) {
                    codes = data.data;
                }
                
                if (codes.length > 0) {
                    const gridRows = codes.map(item => {
                        if (Array.isArray(item) && item.length >= 2) {
                            return {
                                code: String(item[0] || ''),
                                name: String(item[1] || ''),
                                p1: '', // Root level - p1 хоосон, код нь дараагийн level-д p1 болно
                                p2: '',
                                p3: '',
                                p4: '',
                                p5: '',
                                p6: ''
                            };
                        }
                        return null;
                    }).filter(row => row !== null);
                    
                    setGridData(gridRows);
                    setCurrentParams({ p1: '', p2: '', p3: '', p4: '', p5: '', p6: '' });
                } else {
                    console.warn('No classification codes found');
                    setGridData([]);
                }
            } else {
                console.warn('Failed to load classification codes from tax system');
                setGridData([]);
            }
        } catch (error) {
            console.error('Error loading classification codes:', error);
            setGridData([]);
        } finally {
            setLoading(false);
        }
    };

    // Сонгосон мөрөөс параметрүүдийг авч дахин дуудах
    const loadWithSelectedParams = async (row) => {
        setLoading(true);
        try {
            // API endpoint format:
            // - With p1 only: /api/info/check/barcode/v2/{p1}
            // - With more params: /api/info/check/barcode/v2/{p1}/{p2}/{p3}...
            const code = row.code || '';
            const rowP1 = row.p1 || '';
            const rowP2 = row.p2 || '';
            const rowP3 = row.p3 || '';
            const rowP4 = row.p4 || '';
            const rowP5 = row.p5 || '';
            const rowP6 = row.p6 || '';
            
            console.log('Row selected:', { code, rowP1, rowP2, rowP3, rowP4, rowP5, rowP6 });
            
            // Дараагийн level-ийн параметрийг тохируулах
            // Row-ийн одоогийн параметрүүдийг авч, сонгосон кодыг дараагийн level-д нэмнэ
            let p1 = rowP1;
            let p2 = rowP2;
            let p3 = rowP3;
            let p4 = rowP4;
            let p5 = rowP5;
            let p6 = rowP6;
            
            // Дараагийн level-ийн параметрийг олох - эхний хоосон параметрийг сонгосон код болгох
            if (!p1) {
                p1 = code;
            } else if (!p2) {
                p2 = code;
            } else if (!p3) {
                p3 = code;
            } else if (!p4) {
                p4 = code;
            } else if (!p5) {
                p5 = code;
            } else if (!p6) {
                p6 = code;
            }
            
            // API URL бүрдүүлэх - параметрүүдийг дараалан нэмнэ: /api/info/check/barcode/v2/{p1}/{p2}/{p3}...
            const urlParts = ['https://api.ebarimt.mn/api/info/check/barcode/v2'];
            
            // Параметрүүдийг дараалан нэмнэ (зөвхөн хоосон биш параметрүүдийг)
            if (p1) urlParts.push(p1);
            if (p2) urlParts.push(p2);
            if (p3) urlParts.push(p3);
            if (p4) urlParts.push(p4);
            if (p5) urlParts.push(p5);
            if (p6) urlParts.push(p6);
            
            const apiUrl = urlParts.join('/');
            
            console.log('Loading with params:', { code, p1, p2, p3, p4, p5, p6, apiUrl });
            
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                
                // Response формат: [["01", "Нэр"], ["02", "Нэр"], ...]
                let childrenCodes = [];
                if (data && Array.isArray(data)) {
                    childrenCodes = data;
                } else if (data && data.data && Array.isArray(data.data)) {
                    childrenCodes = data.data;
                } else if (data && data.status === 200 && data.data && Array.isArray(data.data)) {
                    childrenCodes = data.data;
                }
                
                console.log('Children codes received:', childrenCodes.length);
                
                if (childrenCodes.length > 0) {
                    const gridRows = childrenCodes.map(item => {
                        if (Array.isArray(item) && item.length >= 2) {
                            const childCode = String(item[0] || '');
                            return {
                                code: childCode,
                                name: String(item[1] || ''),
                                p1: p1,
                                p2: p2,
                                p3: p3,
                                p4: p4,
                                p5: p5,
                                p6: p6
                            };
                        }
                        return null;
                    }).filter(row => row !== null);
                    
                    console.log('Setting grid data with', gridRows.length, 'rows');
                    setGridData(gridRows);
                    setCurrentParams({ p1, p2, p3, p4, p5, p6 });
                } else {
                    // Children байхгүй бол одоогийн grid-ийг хадгалах
                    console.log('No children found for selected code:', code);
                }
            } else {
                const errorText = await response.text();
                console.warn('Failed to load classification codes with selected parameters:', response.status, errorText);
            }
        } catch (error) {
            console.error('Error loading classification codes with selected parameters:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSelect = (code, name) => {
        // 7 оронтой код эсэхийг шалгах
        const is7Digit = code && code.length === 7 && /^\d{7}$/.test(code);
        
        // Зөвхөн 7 оронтой кодыг бараанд бүртгэнэ
        if (is7Digit) {
            if (onSelect) {
                onSelect(code, name);
            }
            if (onClose) {
                onClose();
            }
        } else {
            // 7 оронтой биш бол сонголт хийхгүй
            console.log('Selected code is not 7 digits, cannot register:', code);
        }
    };

    const handleRowDoubleClick = (row) => {
        // 7 оронтой код эсэхийг шалгах
        const is7Digit = row.code && row.code.length === 7 && /^\d{7}$/.test(row.code);
        
        if (is7Digit) {
            // 7 оронтой код бол бараанд бүртгэнэ
            handleSelect(row.code, row.name);
        } else {
            // 7 оронтой биш бол параметрүүдээр дахин дуудах
            loadWithSelectedParams(row);
        }
    };

    // Хайлтын шүүлт
    const filteredGridData = gridData.filter(row => {
        if (!searchTerm) return true;
        const searchLower = searchTerm.toLowerCase();
        return (
            (row.code && row.code.toLowerCase().includes(searchLower)) ||
            (row.name && row.name.toLowerCase().includes(searchLower))
        );
    });

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '800px', maxHeight: '80vh', overflowY: 'auto' }}>
                <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' }}>
                    {/* Search */}
                    <div style={{ marginBottom: '12px', display: 'flex', gap: '8px' }}>
                        <input
                            type="text"
                            className="form-input"
                            placeholder="Хайх (код эсвэл нэр)..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            onKeyPress={(e) => {
                                if (e.key === 'Enter' && searchTerm.trim()) {
                                    // Search is handled by filteredGridData automatically
                                }
                            }}
                            style={{ flex: 1, fontSize: '13px', padding: '8px' }}
                        />
                        <button
                            className="btn btn-secondary"
                            onClick={loadRootClassificationCodes}
                            disabled={loading}
                            style={{ padding: '8px 16px', fontSize: '13px', whiteSpace: 'nowrap' }}
                            title="Эхлэх"
                        >
                            🔄 Эхлэх
                        </button>
                    </div>

                    {/* Breadcrumb */}
                    {(currentParams.p1 || currentParams.p2 || currentParams.p3 || currentParams.p4 || currentParams.p5 || currentParams.p6) && (
                        <div style={{ marginBottom: '12px', padding: '8px', backgroundColor: '#e3f2fd', borderRadius: '4px', fontSize: '12px' }}>
                            <button
                                onClick={loadRootClassificationCodes}
                                style={{
                                    background: 'transparent',
                                    border: 'none',
                                    color: '#1976d2',
                                    cursor: 'pointer',
                                    textDecoration: 'underline',
                                    padding: 0,
                                    marginRight: '8px'
                                }}
                            >
                                Эхлэх
                            </button>
                            <span style={{ color: '#666' }}>
                                {currentParams.p1 && `p1:${currentParams.p1}`}
                                {currentParams.p2 && ` > p2:${currentParams.p2}`}
                                {currentParams.p3 && ` > p3:${currentParams.p3}`}
                                {currentParams.p4 && ` > p4:${currentParams.p4}`}
                                {currentParams.p5 && ` > p5:${currentParams.p5}`}
                                {currentParams.p6 && ` > p6:${currentParams.p6}`}
                            </span>
                        </div>
                    )}

                    {/* Grid View */}
                    <div style={{ 
                        border: '1px solid #ddd', 
                        borderRadius: '4px',
                        overflow: 'hidden',
                        backgroundColor: '#fff'
                    }}>
                        <table style={{ 
                            width: '100%', 
                            borderCollapse: 'collapse',
                            fontSize: '13px'
                        }}>
                            <thead>
                                <tr style={{ backgroundColor: '#f5f5f5', borderBottom: '2px solid #ddd' }}>
                                    <th style={{ padding: '10px', textAlign: 'left', fontWeight: 'bold', borderRight: '1px solid #ddd' }}>Код</th>
                                    <th style={{ padding: '10px', textAlign: 'left', fontWeight: 'bold' }}>Нэр</th>
                                </tr>
                            </thead>
                            <tbody>
                                {loading ? (
                                    <tr>
                                        <td colSpan="2" style={{ padding: '20px', textAlign: 'center', color: '#666' }}>
                                            Ачааллаж байна...
                                        </td>
                                    </tr>
                                ) : filteredGridData.length > 0 ? (
                                    filteredGridData.map((row, index) => {
                                        const is7Digit = row.code && row.code.length === 7 && /^\d{7}$/.test(row.code);
                                        const isSelected = selectedCode === row.code;
                                        
                                        return (
                                            <tr
                                                key={`${row.code}-${index}`}
                                                onDoubleClick={() => handleRowDoubleClick(row)}
                                                style={{
                                                    cursor: 'pointer',
                                                    backgroundColor: isSelected ? '#e3f2fd' : (index % 2 === 0 ? '#fff' : '#f9f9f9'),
                                                    borderBottom: '1px solid #eee',
                                                    transition: 'background-color 0.2s'
                                                }}
                                                onMouseEnter={(e) => {
                                                    if (!isSelected) {
                                                        e.currentTarget.style.backgroundColor = '#f0f0f0';
                                                    }
                                                }}
                                                onMouseLeave={(e) => {
                                                    if (!isSelected) {
                                                        e.currentTarget.style.backgroundColor = index % 2 === 0 ? '#fff' : '#f9f9f9';
                                                    }
                                                }}
                                            >
                                                <td style={{ 
                                                    padding: '10px', 
                                                    borderRight: '1px solid #eee',
                                                    fontWeight: is7Digit ? 'bold' : 'normal',
                                                    color: is7Digit ? '#1976d2' : '#333'
                                                }}>
                                                    {row.code}
                                                </td>
                                                <td style={{ padding: '10px' }}>
                                                    {row.name}
                                                    {is7Digit && (
                                                        <span style={{ 
                                                            marginLeft: '8px', 
                                                            fontSize: '11px', 
                                                            color: '#28a745',
                                                            fontWeight: 'bold'
                                                        }}>
                                                            (БҮНА код)
                                                        </span>
                                                    )}
                                                </td>
                                            </tr>
                                        );
                                    })
                                ) : (
                                    <tr>
                                        <td colSpan="2" style={{ padding: '20px', textAlign: 'center', color: '#666' }}>
                                            Ангилалын код олдсонгүй
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                    {/* Instructions */}
                    <div style={{ marginTop: '12px', padding: '8px', backgroundColor: '#e3f2fd', borderRadius: '4px', fontSize: '12px', color: '#1976d2' }}>
                        <strong>Заавар:</strong> Мөрийг хоёр удаа дарж сонгох. 7 оронтой код (БҮНА код) сонгосон үед бараанд бүртгэнэ.
                    </div>
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={loadRootClassificationCodes} disabled={loading}>
                        Эхлэх
                    </button>
                    <button className="btn btn-secondary" onClick={onClose}>
                        Хаах
                    </button>
                </div>
            </div>
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.ClassificationCodeModal = ClassificationCodeModal;
}

// Export for Node.js/CommonJS
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        ClassificationCodeModal
    };
}
