import EditableInput from './EditableInput.js';

class PropertyTableModel {
    constructor(properties = []) {
        this.properties = properties;
    }

    addProperty(property) {
        this.properties.push(property);
    }

    removeProperty(index) {
        this.properties.splice(index, 1);
    }

    getProperties() {
        return this.properties;
    }

    setProperties(newProperties) {
        this.properties = newProperties;
    }
}

class PropertyTableView {
    constructor(model, controller) {
        this.model = model;
        this.controller = controller;
        this.modelViewList = [];
    }

    render(element) {
        this.element = element;
        this.element.innerHTML = this.generateTableHtml();
        this.attachEventListeners();
    }

    generateTableHtml() {
        const properties = this.model.getProperties();
        let rowsHtml = properties.map((property, index) => this.generateRowHtml(property, index)).join('');

        return `<div class="prop-table">
                    <div class="prop-table-row prop-table-header">
                        <div class="prop-table-cell" style="width: 50px;">#</div>
                        <div class="prop-table-cell" style="flex: 1">이름</div>
                        <div class="prop-table-cell" style="flex: 1">값</div>
                        <div class="prop-table-cell" style="width:100px;">
                            <button type="button" class="btn btn-secondary btn-sm add_property">추가</button>
                        </div>
                    </div>
                    ${rowsHtml}
                </div>`;
    }

    generateRowHtml(property, index) {
        // Updated to include placeholders for EditableInput
        return `
            <div class="prop-table-row" data-index="${index}">
                <div class="prop-table-cell" style="width: 50px;">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" data-name="enabled" ${property.enabled ? 'checked' : ''} />
                    </div>
                </div>
                <div class="prop-table-cell key" style="flex: 1">
                    <div class="editable" data-name="key" data-value="${property.key}"></div>
                </div>
                <div class="prop-table-cell value" style="flex: 1">
                    <div class="editable" data-name="value" data-value="${property.value}"></div>
                </div>
                <div class="prop-table-cell" style="width:100px;">
                    <button type="button" class="btn btn-secondary btn-sm remove-property" data-index="${index}">
                        <i class="fa fa-sharp fa-minus" data-index="${index}"></i>
                    </button>
                </div>
            </div>
        `;
    }

    updateUI() {
        // Re-render the table with updated data
        this.element.innerHTML = this.generateTableHtml();
        // Instantiate EditableInput components for each editable cell
        this.element.querySelectorAll('.prop-table-row:not(.prop-table-header)').forEach((row, index) => {

            const checkbox = row.querySelector('.form-check-input');
            if (checkbox) {
                checkbox.addEventListener('change', (event) => {
                    const index = parseInt(event.target.parentElement.parentElement.parentElement.getAttribute('data-index'), 10);
                    this.controller.updateProperty(index, 'enabled', event.target.checked);
                    if (this.controller.additionalCallback) {
                        this.controller.additionalCallback(this.model.getProperties());
                    }
                });
            }

            this.element.querySelectorAll('.editable').forEach(editableElement => {
                const index = parseInt(editableElement.parentElement.parentElement.getAttribute('data-index'), 10);
                const editableInput = new EditableInput({
                    name: editableElement.dataset.name,
                    value: editableElement.dataset.value
                });

                editableInput.init(editableElement, (value) => {
                    let model = this.model.getProperties()[index];
                    model[editableElement.dataset.name] = value;
                    if (this.controller.additionalCallback) {
                        this.controller.additionalCallback(this.model.getProperties());
                    }
                });
            });
        });

        this.attachEventListeners();
    }


    attachEventListeners() {
        this.element.querySelectorAll('.remove-property').forEach(button => {
            button.addEventListener('click', (event) => {
                console.log(event.target);
                console.log(event.target.getAttribute('data-index'));
                const index = parseInt(event.target.getAttribute('data-index'), 10);
                console.log({index});
                this.controller.removeProperty(index);
            });
        });

        const addButton = this.element.querySelector('.add_property');
        if (addButton) {
            addButton.addEventListener('click', (event) => {
                this.controller.addProperty();
            });
        } else {
            console.log('Add button not found'); // Check if the button is not found
        }
    }
}


class PropertyTableController {
    constructor(model) {
        this.model = model;
        this.view = new PropertyTableView(this.model, this);
    }

    init(element, callback) {
        this.view.render(element);
        this.additionalCallback = callback;
    }

    addProperty() {
        console.log('addProperty');
        // Add a new property to the model
        this.model.addProperty({
            key: '',
            value: ''
        });
        // Update the view to reflect the model changes
        this.view.updateUI();
    }

    removeProperty(index) {
        // Remove the property from the model
        this.model.removeProperty(index);
        // Update the view to reflect the model changes
        this.view.updateUI();
        if (this.additionalCallback) {
            this.additionalCallback(this.model.getProperties());
        }
    }

    updateProperty(index, key, value) {
        // Update a specific property in the model
        let properties = this.model.getProperties();
        if (properties[index]) {
            properties[index][key] = value;
        }
    }

    updateUI() {
        this.view.updateUI();
    }
}

class PropertyTable {
    constructor(options = {}) {
        this.model = new PropertyTableModel(options.properties || []);
        this.controller = new PropertyTableController(this.model);
        this.propertyName = options.propertyName || '';
    }

    init(element, callback) {
        // Initialize the controller with the DOM element
        this.controller.init(element, callback);
        this.setProperties(this.model.getProperties());
    }

    getProperties() {
        // Delegate to the model
        return this.model.getProperties();
    }

    setProperties(newProperties) {
        // Update the model and refresh the view
        this.model.setProperties(newProperties);
        this.controller.updateUI();
    }

    addProperty(property) {
        // Delegate to the controller
        this.controller.addProperty(property);
    }

    removeProperty(index) {
        // Delegate to the controller
        this.controller.removeProperty(index);

    }

    // Any additional methods as needed
}


export default PropertyTable;
