<script type="module">
window.EveAI = window.EveAI || {};
window.EveAI.OrderedListEditors = {
    instances: {},
    initialize: function(containerId, data, listType, options = {}) {
        console.log('Initializing OrderedListEditor for', containerId, 'with data', data, 'and listType', listType);
        const container = document.getElementById(containerId);
        if (!container || typeof container !== 'object' || !('classList' in container)) {
            console.error(`Container with ID ${containerId} not found or not a valid element:`, container);
            return null;
        }

        if (this.instances[containerId]) return this.instances[containerId];

        if (typeof window.Tabulator !== 'function') {
            console.error('Tabulator not loaded (window.Tabulator missing).');
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error:</strong> Tabulator not loaded
            </div>`;
            return null;
        }

        // Get the list type configuration
        const listTypeConfig = this._getListTypeConfig(listType);
        if (!listTypeConfig) {
            console.error(`List type configuration for ${listType} not found.`);
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error:</strong> List type configuration for ${listType} not found
            </div>`;
            return null;
        }

        // Create column definitions from list type
        const columns = this._createColumnsFromListType(listTypeConfig);

        // Debug log for data and columns
        console.log('Data for Tabulator:', data);
        console.log('Columns for Tabulator:', columns);

        // Debug log for column titles
        console.log('Column titles:', columns.map(col => col.title || ''));

        // Initialize Tabulator
        try {
            console.log('Creating Tabulator for', containerId);
            const table = new Tabulator(container, {
                data: data || [],
                columns: columns,
                layout: "fitColumns", // Changed to fitColumns to ensure columns display horizontally
                movableRows: true,
                movableRowsPlaceholder: false, // Don't use placeholder, show actual row content
                movableRowsSender: "table", // Keep a copy of the row in the table while dragging
                rowHeader: {headerSort:false, resizable: false, minWidth:30, width:30, rowHandle:true, formatter:"handle"},
                maxHeight: "50%", // Auto height to display all rows
                placeholder: "No Data Available",
                autoResize: false,
                resizableColumnFit: true,
                responsiveLayout: false,
                tooltips: true, // Enable tooltips
                tooltipsHeader: true,
                selectable: false, // Disable row selection to prevent jumping
                selectableRangeMode: "click", // Only select on click, not on drag
                selectableRollingSelection: false, // Disable rolling selection
                scrollToRowIfVisible: false, // Don't scroll to row even if it's already visible
                scrollToRowPosition: "nearest",
                ...options
            });

            console.log('Tabulator created for', containerId);
            container.classList.add('tabulator-initialized');

            // Debug: Log table structure
            console.log('Table structure:', {
                tableElement: container,
                tableData: table.getData(),
                tableColumns: table.getColumnDefinitions()
            });

            // Add row button
            const addRowBtn = document.createElement('button');
            addRowBtn.className = 'btn btn-sm btn-primary mt-2';
            addRowBtn.type = 'button'; // Deze regel toevoegen om submit te voorkomen
            addRowBtn.innerHTML = 'Add Row';
            addRowBtn.addEventListener('click', (e) => {
                e.preventDefault(); // Extra veiligheid om submit te voorkomen
                const newRow = {};
                // Create empty row with default values
                Object.entries(listTypeConfig).forEach(([key, field]) => {
                    if (field.type === 'boolean') {
                        newRow[key] = field.default === true;
                    } else {
                        newRow[key] = field.default !== undefined ? field.default : '';
                    }
                });
                table.addRow(newRow);
                this._updateTextarea(containerId, table);
            });

            container.parentNode.insertBefore(addRowBtn, container.nextSibling);

            // Store instance
            this.instances[containerId] = {
                table: table,
                textarea: document.getElementById(containerId.replace('-editor', ''))
            };

            // Prevent scrolling when clicking on cells
            container.addEventListener('click', function(e) {
                // Prevent the default behavior which might cause scrolling
                if (e.target.closest('.tabulator-cell')) {
                    e.preventDefault();
                }
            }, { passive: false });

            // Update textarea on various events that change data
            table.on("dataChanged", () => {
                console.log("dataChanged event triggered");
                this._updateTextarea(containerId, table);
            });

            // Listen for row movement
            table.on("rowMoved", () => {
                console.log("rowMoved event triggered");
                this._updateTextarea(containerId, table);
            });

            // Listen for cell edits
            table.on("cellEdited", () => {
                console.log("cellEdited event triggered");
                this._updateTextarea(containerId, table);
            });

            return table;
        } catch (e) {
            console.error(`Error initializing Tabulator for ${containerId}:`, e);
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error initializing Tabulator:</strong><br>${e.message}
            </div>`;
            return null;
        }
    },

    _updateTextarea: function(containerId, table) {
        const instance = this.instances[containerId];
        if (instance && instance.textarea) {
            const data = table.getData();
            console.log('Updating textarea with data:', data);
            instance.textarea.value = JSON.stringify(data);
            console.log('Textarea value updated:', instance.textarea.value);

            // Trigger change event on textarea to ensure form validation recognizes the change
            const event = new Event('change', { bubbles: true });
            instance.textarea.dispatchEvent(event);

            // Also trigger input event for any listeners that might be using that
            const inputEvent = new Event('input', { bubbles: true });
            instance.textarea.dispatchEvent(inputEvent);
        } else {
            console.error('Cannot update textarea: instance or textarea not found for', containerId);
        }
    },

    _getListTypeConfig: function(listType) {
        // Try to get the list type configuration from window.listTypeConfigs
        if (window.listTypeConfigs && window.listTypeConfigs[listType]) {
            return window.listTypeConfigs[listType];
        }

        // If not found, log a warning and return a default configuration
        console.warn(`List type configuration for ${listType} not found in window.listTypeConfigs. Using a default configuration.`);
        return {
            title: {
                name: "Title",
                description: "Title",
                type: "str",
                required: true
            },
            description: {
                name: "Description",
                description: "Description",
                type: "text",
                required: true
            }
        };
    },

    // Custom formatter for text columns to truncate text in normal mode
    _truncateFormatter: function(cell, formatterParams, onRendered) {
        const value = cell.getValue();
        const maxLength = formatterParams.maxLength || 100;

        if (value && value.length > maxLength) {
            // Create a truncated version with "..." and show more indicator
            const truncated = value.substring(0, maxLength) + "...";

            // Return HTML with truncated text and a "show more" button
            return `<div class="truncated-cell">
                      <div class="truncated-content">${truncated}</div>
                      <div class="show-more" title="Click to edit and see full text">
                        <i class="material-icons">more_horiz</i>
                      </div>
                    </div>`;
        }

        return value;
    },

    _createColumnsFromListType: function(listTypeConfig) {
        const columns = [];

        // Add columns for each field in the list type
        Object.entries(listTypeConfig).forEach(([key, field]) => {
            const column = {
                title: field.name || key,
                field: key,
                headerTooltip: field.description,
                headerSort: false,
                visible: true,
                resizable: "header",
            };
            console.log("Column ", field.name, " type: ", field.type)
            // Set width based on field type
            if (field.type === 'boolean') {
                column.minWidth = 50;
                column.maxWidth = 80; // Limit maximum width
                column.widthGrow = 0; // Don't allow boolean columns to grow
            } else if (field.type === 'text') {
                column.width = 400; // Much larger width for text columns (especially description)
                column.minWidth = 300; // Ensure text columns have adequate minimum width
                column.widthGrow = 2; // Allow text columns to grow significantly more
            } else {
                column.width = 150; // Default width for other columns
                column.minWidth = 100;
                column.widthGrow = 1; // Allow some growth
            }

            // Ensure consistent width calculation
            column.widthShrink = 0; // Don't allow shrinking below minWidth

            // Set editor based on field type
            if (field.type === 'boolean') {
                column.formatter = 'tickCross';
                column.editor = 'tickCross';
                column.hozAlign = 'center';
                column.headerHozAlign = 'center';
                column.formatterParams = {
                    allowEmpty: true,
                    allowTruthy: true,
                    tickElement: "<i class='material-icons'>check_circle</i>",
                    crossElement: "<i class='material-icons'>cancel</i>"
                };
            } else if (field.type === 'enum' && field.allowed_values) {
                column.editor = 'select';
                column.editorParams = {
                    values: field.allowed_values
                };
                column.hozAlign = 'left';
                column.headerHozAlign = 'left';
            } else if (field.type === 'text') {
                column.editor = 'textarea';
                column.formatter = this._truncateFormatter; // Use custom formatter to truncate text
                column.variableHeight = true;
                // Configure formatter parameters
                column.formatterParams = {
                    maxLength: 50,
                    autoResize: true
                };
                // Prevent scrolling when editing text cells
                column.editorParams = {
                    elementAttributes: {
                        preventScroll: true
                    }
                };
                column.hozAlign = 'left';
                column.headerHozAlign = 'left';
            } else {
                column.editor = 'input';
                column.hozAlign = 'left';
                column.headerHozAlign = 'left';
            }

            columns.push(column);
        });

        // We don't add a delete button column as per requirements
        // to prevent users from deleting rows

        return columns;
    },

    get: function(containerId) {
        return this.instances[containerId] || null;
    },

    destroy: function(containerId) {
        if (this.instances[containerId]) {
            if (this.instances[containerId].table && typeof this.instances[containerId].table.destroy === 'function') {
                this.instances[containerId].table.destroy();
            }
            delete this.instances[containerId];
        }
        const container = document.getElementById(containerId);
        if (container) {
            container.classList.remove('tabulator-initialized');
            container.innerHTML = '';
        }
    }
};

document.addEventListener('DOMContentLoaded', function() {
    // Initialize list type configurations
    window.listTypeConfigs = window.listTypeConfigs || {};

    // Initialize ordered list editors
    document.querySelectorAll('.ordered-list-field').forEach(function(textarea) {
        const containerId = textarea.id + '-editor';
        console.log('Initializing ordered list editor for', containerId);

        // Create container if it doesn't exist
        let container = document.getElementById(containerId);
        if (!container) {
            container = document.createElement('div');
            container.id = containerId;
            container.className = 'ordered-list-editor';
            textarea.parentNode.insertBefore(container, textarea.nextSibling);
            textarea.classList.add('d-none'); // Hide the textarea
        }

        try {
            const data = textarea.value ? JSON.parse(textarea.value) : [];
            const listType = textarea.getAttribute('data-list-type');

            // Check if we have the list type configuration
            if (listType && !window.listTypeConfigs[listType]) {
                console.warn(`List type configuration for ${listType} not found. Using default configuration.`);
            }

            window.EveAI.OrderedListEditors.initialize(containerId, data, listType);
        } catch (e) {
            console.error('Error initializing ordered list editor:', e);
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error initializing ordered list editor:</strong><br>${e.message}
            </div>`;
        }
    });
});
</script>

