class TextInput {
    constructor(options = {}) {
        this.options = {
            containerId: options.containerId || null,
            id: options.id || this.generateId(),
            name: options.name || options.id || this.generateId(),
            label: options.label || '',
            type: options.type || 'text',
            placeholder: options.placeholder || '',
            defaultValue: options.defaultValue || '',
            required: options.required || false,
            validation: options.validation || null,
            onChange: options.onChange || null,
            className: options.className || '',
            helpText: options.helpText || null,
            ...options
        };

        this.container = null;
        this.inputElement = null;
        this.labelElement = null;
        this.errorElement = null;
        this.helpTextElement = null;
        this.isValid = true;

        this.init();
    }

    generateId() {
        return 'text-input-' + Math.random().toString(36).substr(2, 9);
    }

    init() {
        if (this.options.containerId) {
            this.container = document.getElementById(this.options.containerId);
            if (!this.container) {
                console.error(`TextInput: Container with ID "${this.options.containerId}" not found`);
                return;
            }
            this.render();
        }
    }

    render() {
        if (!this.container) return;

        const formGroupClass = `form-group text-input-component ${this.options.className}`.trim();

        this.container.innerHTML = `
            <div class="${formGroupClass}">
                <label for="${this.options.id}">${this.options.label}${this.options.required ? ' *' : ''}</label>
                <input
                    type="${this.options.type}"
                    id="${this.options.id}"
                    name="${this.options.name}"
                    placeholder="${this.options.placeholder}"
                    value="${this.options.defaultValue}"
                    ${this.options.required ? 'required' : ''}
                    class="text-input-field"
                />
                ${this.options.helpText ? `<div class="text-input-help-text">${this.options.helpText}</div>` : ''}
                <div class="text-input-error" style="display: none;"></div>
            </div>
        `;

        this.inputElement = this.container.querySelector(`#${this.options.id}`);
        this.labelElement = this.container.querySelector('label');
        this.errorElement = this.container.querySelector('.text-input-error');
        this.helpTextElement = this.container.querySelector('.text-input-help-text');

        this.attachEventListeners();
    }

    attachEventListeners() {
        if (!this.inputElement) return;

        this.inputElement.addEventListener('input', (e) => {

            if (this.errorElement && this.errorElement.style.display !== 'none') {
                this.showError('');
            }

            if (this.options.onChange) {
                this.options.onChange(e.target.value, this);
            }
        });
    }

    validateInput() {
        const value = this.getValue();
        let isValid = true;
        let errorMessage = '';

        if (this.options.required && !value.trim()) {
            isValid = false;
            errorMessage = `${this.options.label} is required`;
        }

        if (isValid && this.options.validation && typeof this.options.validation === 'function') {
            const validationResult = this.options.validation(value);
            if (validationResult !== true) {
                isValid = false;
                errorMessage = validationResult || 'Invalid input';
            }
        }

        this.isValid = isValid;
        this.showError(isValid ? '' : errorMessage);

        return isValid;
    }

    showError(message) {
        if (!this.errorElement) return;

        if (message) {
            this.errorElement.textContent = message;
            this.errorElement.style.display = 'block';
            this.inputElement.classList.add('error');
        } else {
            this.errorElement.style.display = 'none';
            this.inputElement.classList.remove('error');
        }
    }

    getValue() {
        return this.inputElement ? this.inputElement.value : '';
    }

    setValue(value) {
        if (this.inputElement) {
            this.inputElement.value = value || '';

        }
    }

    clear() {
        this.setValue('');
    }

    focus() {
        if (this.inputElement) {
            this.inputElement.focus();
        }
    }

    setEnabled(enabled) {
        if (this.inputElement) {
            this.inputElement.disabled = !enabled;
        }
    }

    validate() {
        return this.validateInput();
    }

    getData() {
        return {
            [this.options.name]: this.getValue()
        };
    }

    setData(data) {
        if (data && data[this.options.name] !== undefined) {
            this.setValue(data[this.options.name]);
        }
    }

    destroy() {
        if (this.container) {
            this.container.innerHTML = '';
        }
        this.inputElement = null;
        this.labelElement = null;
        this.errorElement = null;
        this.helpTextElement = null;
        this.container = null;
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = TextInput;
}