// Type Modal Component for CRUD operations on a_type table
const { useState, useEffect } = React;

function TypeModal({ 
    isOpen, 
    onClose,
    types,
    onRefresh,
    api,
    showAlert,
    showConfirm
}) {
    const [type, setType] = useState({
        type_name: ''
    });
    const [isEditing, setIsEditing] = useState(false);
    const [selectedTypeId, setSelectedTypeId] = useState(null);
    const [loading, setLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        if (isOpen && !isEditing) {
            setType({ type_name: '' });
            setSelectedTypeId(null);
            setSearchTerm('');
        }
    }, [isOpen, isEditing]);

    const handleEdit = async (type_id) => {
        try {
            setLoading(true);
            const result = await api.getTypeById(type_id);
            if (result.success && result.data) {
                const t = result.data;
                setType({
                    type_name: t.type_name || ''
                });
                setSelectedTypeId(type_id);
                setIsEditing(true);
            } else {
                showAlert('Төрөл олдсонгүй!');
            }
        } catch (error) {
            console.error('Error loading type:', error);
            showAlert('Төрөл ачаалахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (type_id) => {
        const confirmMessage = 'Энэ төрлийг устгахдаа итгэлтэй байна уу?';
        if (showConfirm && typeof showConfirm === 'function') {
            showConfirm(confirmMessage, () => {
                // Continue with delete
                performDelete(type_id);
            });
            return;
        }
        // Fallback - if no showConfirm, don't delete
        return;
    };
    
    const performDelete = async (type_id) => {
        
        try {
            setLoading(true);
            const result = await api.deleteType(type_id);
            if (result.success) {
                showAlert('Төрөл амжилттай устгагдлаа!');
                if (onRefresh) {
                    await onRefresh();
                }
                if (selectedTypeId === type_id) {
                    setIsEditing(false);
                    setSelectedTypeId(null);
                }
            } else {
                showAlert('Төрөл устгахад алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
            }
        } catch (error) {
            console.error('Error deleting type:', error);
            showAlert('Төрөл устгахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async () => {
        if (!type.type_name || type.type_name.trim() === '') {
            showAlert('Төрлийн нэр заавал оруулах шаардлагатай!');
            return;
        }

        try {
            setLoading(true);
            const typeData = {
                type_name: type.type_name.trim()
            };

            let result;
            if (isEditing && selectedTypeId) {
                result = await api.updateType(selectedTypeId, typeData);
            } else {
                result = await api.createType(typeData);
            }

            if (result.success) {
                showAlert(isEditing ? 'Төрөл амжилттай шинэчлэгдлээ!' : 'Төрөл амжилттай нэмэгдлээ!');
                if (onRefresh) {
                    await onRefresh();
                }
                setIsEditing(false);
                setSelectedTypeId(null);
            } else {
                showAlert('Хадгалахад алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
            }
        } catch (error) {
            console.error('Error saving type:', error);
            showAlert('Хадгалахад алдаа гарлаа: ' + (error.message || error));
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        setIsEditing(false);
        setSelectedTypeId(null);
        setType({ type_name: '' });
    };

    const filteredTypes = types?.filter(t => {
        if (!searchTerm) return true;
        const search = searchTerm.toLowerCase();
        return (t.type_name && t.type_name.toLowerCase().includes(search));
    }) || [];

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '500px', maxHeight: '80vh', overflowY: 'auto' }}>
                <div className="modal-header">
                    <h2 style={{ fontSize: '16px', margin: 0 }}>Барааны төрөл (a_type)</h2>
                    <button className="modal-close" onClick={onClose} style={{ fontSize: '20px' }}>×</button>
                </div>
                
                <div className="modal-body" style={{ padding: '12px', fontSize: '13px' }}>
                    {/* Type List */}
                    <div style={{ marginBottom: '12px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                            <h3 style={{ margin: 0, fontSize: '15px' }}>Төрлийн жагсаалт</h3>
                            <button
                                className="btn btn-primary"
                                onClick={handleCancel}
                                style={{ padding: '4px 8px', fontSize: '12px' }}
                            >
                                + Шинэ төрөл
                            </button>
                        </div>
                        <input
                            type="text"
                            className="form-input"
                            placeholder="Хайх..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            style={{ marginBottom: '6px', width: '100%', fontSize: '12px', padding: '4px 8px' }}
                        />
                        <div style={{ maxHeight: '250px', overflowY: 'auto', border: '1px solid #ddd', borderRadius: '4px' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>
                                <thead>
                                    <tr style={{ background: '#f5f5f5', position: 'sticky', top: 0 }}>
                                        <th style={{ padding: '5px', textAlign: 'left', borderBottom: '1px solid #ddd', fontSize: '12px' }}>Төрлийн нэр</th>
                                        <th style={{ padding: '5px', textAlign: 'center', borderBottom: '1px solid #ddd', width: '150px', fontSize: '12px' }}>Үйлдэл</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {filteredTypes.length === 0 ? (
                                        <tr>
                                            <td colSpan="2" style={{ padding: '12px', textAlign: 'center', color: '#999', fontSize: '12px' }}>
                                                Төрөл олдсонгүй
                                            </td>
                                        </tr>
                                    ) : (
                                        filteredTypes.map((t) => (
                                            <tr key={t.type_id} style={{ borderBottom: '1px solid #eee' }}>
                                                <td style={{ padding: '5px', fontSize: '12px' }}>{t.type_name || '-'}</td>
                                                <td style={{ padding: '5px', textAlign: 'center' }}>
                                                    <button
                                                        className="btn btn-secondary"
                                                        onClick={() => handleEdit(t.type_id)}
                                                        style={{ padding: '3px 6px', fontSize: '11px', marginRight: '3px' }}
                                                        disabled={loading}
                                                    >
                                                        Засах
                                                    </button>
                                                    <button
                                                        className="btn btn-danger"
                                                        onClick={() => handleDelete(t.type_id)}
                                                        style={{ padding: '3px 6px', fontSize: '11px' }}
                                                        disabled={loading}
                                                    >
                                                        Устгах
                                                    </button>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Type Form */}
                    <div className="settings-section">
                        <h3 className="settings-section-title">
                            {isEditing ? 'Төрөл засах' : 'Шинэ төрөл нэмэх'}
                        </h3>
                        <div className="settings-grid">
                            <div className="settings-form-group" style={{ gridColumn: '1 / -1' }}>
                                <label>Төрлийн нэр <span>*</span></label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={type.type_name}
                                    onChange={(e) => setType({...type, type_name: e.target.value})}
                                    placeholder="Төрлийн нэр"
                                    disabled={loading}
                                />
                            </div>
                        </div>
                    </div>
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={handleCancel} disabled={loading || !isEditing}>
                        Цуцлах
                    </button>
                    <button className="btn btn-primary" onClick={handleSave} disabled={loading}>
                        {loading ? 'Хадгалж байна...' : (isEditing ? 'Шинэчлэх' : 'Хадгалах')}
                    </button>
                </div>
            </div>
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.TypeModal = TypeModal;
}

