var editMode = true;
const columns = ['ID', 'Work Item Type', 'Title', 'Assigned To', 'State', 'Tags'];
const allOptions = [];

document.addEventListener("DOMContentLoaded", function () {

    const columnList = document.getElementById('column-list');
    const addColumnBtn = document.getElementById('add-column');

    function createRow(selectedValue = '', selectedText = '') {
        const row = document.createElement('div');
        row.className = 'row';
        row.draggable = true;

        const icon = document.createElement('div');
        icon.className = 'row-icon';
        icon.innerHTML = '&#x2630;';

        const inputWrapper = document.createElement('div');
        inputWrapper.className = 'input-wrapper';

        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'search-input';
        searchInput.placeholder = '';

        // Create a new dropdown for each row
        const dropdown = document.createElement('div');
        dropdown.className = 'dropdown';
        dropdown.style.display = 'none';  // Keep the dropdown hidden by default

        // Event listeners for input field
        searchInput.addEventListener('input', () => filterOptions(searchInput, dropdown));

        searchInput.addEventListener('focus', () => {
            dropdown.style.display = 'block';  // Show dropdown when focused
            //filterOptions(searchInput, dropdown);  // Filter dropdown items based on input
        });

        searchInput.addEventListener('blur', () => {
            setTimeout(() => {
                dropdown.style.display = 'none';  // Hide dropdown after a short delay when input loses focus
            }, 200);
        });

        dropdown.addEventListener('click', (e) => {
            const option = e.target;
            if (option && option.classList.contains('dropdown-item')) {
                searchInput.value = option.textContent;

                searchInput.setAttribute('data-reference', $(option).data('reference'))

                populateSelectOptions(searchInput, dropdown);
                dropdown.style.display = 'none';  // Hide dropdown after selection
                updateAllSelectOptions();
            }
        });

        inputWrapper.appendChild(searchInput);
        inputWrapper.appendChild(dropdown);
        row.appendChild(icon);
        row.appendChild(inputWrapper);

        const removeBtn = document.createElement('span');
        removeBtn.innerHTML = '&times;';
        removeBtn.className = 'remove-btn';
        removeBtn.onclick = () => {
            row.remove();
            updateAllSelectOptions();
        };

        row.appendChild(removeBtn);
        addDragHandlers(row);
        columnList.appendChild(row);

        // Populate dropdown options
        populateSelectOptions(searchInput, dropdown);

        if (selectedValue !== '') {
            searchInput.value = selectedText;

            searchInput.setAttribute('data-reference', selectedValue)

            populateSelectOptions(searchInput, dropdown);
            dropdown.style.display = 'none';  // Hide dropdown after selection
            updateAllSelectOptions();
        }

        return row;
    }

    function populateSelectOptions(searchInput, dropdown) {
        const selectedValues = Array.from(document.querySelectorAll('#column-list .search-input'))
            .map(input => input.value);

        dropdown.innerHTML = '';
        allOptions.forEach(option => {
            if (!selectedValues.includes(option.name) || searchInput.value === option.name) {
                const item = document.createElement('div');
                item.className = 'dropdown-item';
                item.textContent = option.name;
                item.setAttribute('data-reference', option.referenceName)

                dropdown.appendChild(item);
            }
        });
    }

    function filterOptions(input, dropdown) {
        const query = input.value.toLowerCase();
        const items = dropdown.querySelectorAll('.dropdown-item');
        items.forEach(item => {
            const shouldDisplay = item.textContent.toLowerCase().includes(query);
            item.style.display = shouldDisplay ? '' : 'none';
        });
    }

    function updateAllSelectOptions() {
        const inputs = document.querySelectorAll('#column-list .search-input');
        inputs.forEach(input => {
            const currentValue = input.value;
            const dropdown = input.nextElementSibling;
            populateSelectOptions(input, dropdown);
        });

        const selectedValues = Array.from(document.querySelectorAll('#column-list .search-input')).map(input => input.value);
        const availableOptions = allOptions.filter(opt => !selectedValues.includes(opt.name));

        if (availableOptions.length === 0) {
            addColumnBtn.classList.add('disabled');
            addColumnBtn.onclick = null;
        } else {
            addColumnBtn.classList.remove('disabled');
            addColumnBtn.onclick = handleAddColumn;
        }
    }

    function handleAddColumn(selectedValue = '', selectedText = '') {
        if (addColumnBtn.classList.contains('disabled')) return;
        createRow(selectedValue, selectedText);
        updateAllSelectOptions();
    }

    function addDragHandlers(row) {
        row.addEventListener('dragstart', () => {
            row.classList.add('dragging');
        });

        row.addEventListener('dragend', () => {
            row.classList.remove('dragging');
        });

        row.addEventListener('dragover', (e) => {
            e.preventDefault();
            const dragging = document.querySelector('.dragging');
            const afterElement = getDragAfterElement(columnList, e.clientY);
            if (afterElement == null) {
                columnList.appendChild(dragging);
            } else {
                columnList.insertBefore(dragging, afterElement);
            }
        });
    }

    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.row:not(.dragging)')];

        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    function GetTemplateObject() {
        const rows = columnList.querySelectorAll('.row');
        const result = [];

        rows.forEach((row, index) => {
            const input = row.querySelector('.search-input');
            result.push({
                azureReferenceName: input.dataset.reference,
                columnName: input.value,
                columnOrder: index + 1,
            });
        });

        return result;
        //return JSON.stringify(result, null, 2);
    }

    async function PopulateWorkItemFields() {
        const response = await IndexLibrary.GetRequest({
            endpoint: "/api/AzureDevOps/GetWorkItemFields",
        });
        const workItemFields = await response.json();

        workItemFields.value.forEach(element => {
            var obj = {};
            obj.referenceName = element.referenceName;
            obj.name = element.name;
            allOptions.push(obj);

        });
        allOptions.push({ referenceName: 'custom.User', name: 'User' });
        allOptions.push({ referenceName: 'custom.Project', name: 'Project' })
        allOptions.push({ referenceName: 'custom.WorkType', name: 'Work Type' })
        allOptions.push({ referenceName: 'custom.StartDateTime', name: 'Start DateTime' })
        allOptions.push({ referenceName: 'custom.EndDateTime', name: 'End DateTime' })
        allOptions.push({ referenceName: 'custom.TotalTime', name: 'Total Time (Hours)' })
        allOptions.push({ referenceName: 'custom.IsBillable', name: 'IsBillable' })
    }

    async function CreateTemplate() {
        var templateJSON = GetTemplateObject();
        var templateName = document.getElementById("template-name").value;
        var template = {};
        var columns = document.getElementsByClassName('search-input')
        if (templateName == '') {
            IndexLibrary.ShowToast('error', 'Template name cannot be empty');
            return;
        }
        if (columns.length > 0) {
            for (var i = 0; i < columns.length; i++) {
                if (columns[i].value == '') {
                    IndexLibrary.ShowToast('error', 'Column list cannot contain empty values');
                    return;
                }
            }
        } else {
            IndexLibrary.ShowToast('error', 'Cannot create a template with zero columns')
            return;
        }
        template.templateName = templateName;
        template.templateColumns = templateJSON;
        if (editMode == false) {
            await IndexLibrary.CreateAdvancedReportingTemplate(template);
            await PopulateTemplatesDropdown();
        } else {
            template.templateId = $("#ddlTemplates").val();
            IndexLibrary.UpdateAdvancedReportingTemplate(template);
        }
    }

    async function PopulateTemplatesDropdown() {
        console.log('Populating templates dropdown...after update');
        try {
            const authenticationHeader = await IndexLibrary.GetAccessToken();
            const templates = await IndexLibrary.GetUserReportingTemplates(authenticationHeader);
            const dropdown = document.getElementById('ddlTemplates');

            // Clear existing options
            dropdown.innerHTML = '';

            // Optionally, add a default placeholder
            const defaultOption = document.createElement('option');
            defaultOption.value = '0';
            defaultOption.textContent = '--- Select Template ---';
            dropdown.appendChild(defaultOption);

            // Populate with templates
            templates.forEach(template => {
                const option = document.createElement('option');
                option.value = template.id;
                option.textContent = template.templateName;
                dropdown.appendChild(option);
            });
        } catch (error) {
            console.error('Error populating templates dropdown:', error);
        }
    }

    async function LoadSelectedTemplate() {
        const templateId = $("#ddlTemplates").val();
        if (templateId === "0") { $("#templateDetails").hide(); return; }

        const response = await IndexLibrary.GetRequest({
            endpoint: `/api/TimesheetReportingTemplate/GetById/${templateId}`,
        });
        const template = await response.json();

        $("#template-name").val(template.templateName);
        $("#isShared").prop("checked", template.isShared);
        columnList.innerHTML = "";
        updateAllSelectOptions();
        template.templateColumns.forEach(col => handleAddColumn(col.azureReferenceName, col.columnName));
        $("#templateDetails").show();
    }

    async function NewTemplate() {
        editMode = false;
        columnList.innerHTML = "";
        $("#templateDetails").show();
        $("#templateSelection").hide();
        $("#close-new-template").show();
        $("#template-name").val('');
        $("#isShared").prop("checked", false);
        createRow();
        updateAllSelectOptions();
    }

    async function CloseNewTemplate() {
        editMode = true;
        $("#templateSelection").show();
        $("#templateDetails").hide();
        $("#close-new-template").hide();
        $("#ddlTemplates").val("0");
        columnList.innerHTML = "";
        updateAllSelectOptions();
    }

    $("#btnClosePanel").on('click', () => IndexLibrary.ClosePanel(null));


    window.NewTemplate = NewTemplate;
    window.CloseNewTemplate = CloseNewTemplate;
    window.LoadSelectedTemplate = LoadSelectedTemplate;
    window.CreateTemplate = CreateTemplate;
    window.handleAddColumn = handleAddColumn;
    PopulateWorkItemFields();
    PopulateTemplatesDropdown();
    $("#templateSelection").show();
    $("#templateDetails").hide();
    $("#close-new-template").hide();
});
