import * as utils from "../utility/helper-functions.js";
import * as state from "../state/state.js";
import * as stylesUI from "../components/styles-ui.js";

const parser = new DOMParser();
const gridThemeName = document.querySelector(".grid-theme-name");
const gridThemeClear = document.querySelector(".clear-grid-theme");
const gridThemeSave = document.querySelector(".save-grid-theme");
const gridThemeScopeSelector = document.querySelector(".grid-theme-scope");
const createGridThemeSection = document.querySelector(".grid-themes-section");
const savedGridThemesSection = document.querySelector(".saved-grid-themes-section");

const gridThemeList = [];
const editingGridTheme = {
    status: false,
    name: ""
};

const getGridThemeNode = (uniqueId) => {
    return `
        <li class="saved-grid-theme">
            <span class="grid-theme-label"></span>
            <div class="action-buttons">
                <label for="grid-theme-default-btn-${uniqueId}" class="custom-radio">
                    <input type="radio" name="set-default-grid-theme" id="grid-theme-default-btn-${uniqueId}" class="grid-theme-default">
                    <span class="custom-radio-icon"></span>
                </label>
                <!-- <button class="grid-theme-edit edit-button">Edit</button> -->
                <button class="grid-theme-delete delete-button">Delete</button>
            </div>
        </li>
    `;
};

function getGridThemeList() {
    return gridThemeList;
}

function addThemeToList(value) {
    if (Array.isArray(value)) {
        // Array of themes
        gridThemeList.push(...value);
    } else {
        // Single theme
        gridThemeList.push(value);
    }
}

function emptyThemeOptions() {
    gridThemeScopeSelector.options.length = 0;
    const genericTheme = document.createElement("option");
    genericTheme.value = "global";
    genericTheme.textContent = "None (Global Styles)";
    gridThemeScopeSelector.append(genericTheme);
}

function addOrRemoveThemeFromScope(theme, action) {
    if (action === "add") {
        const themeToAdd = document.createElement("option");
        themeToAdd.value = theme;
        themeToAdd.textContent = theme;
        themeToAdd.setAttribute("data-grid-theme-option", theme);
        gridThemeScopeSelector.append(themeToAdd);
    } else if (action === "remove") {
        const themeToRemove = Array.from(gridThemeScopeSelector.options).find(option => option.dataset.gridThemeOption === theme);
        if (themeToRemove) {
            themeToRemove.remove();
        }
    }
}

function clearGridThemeEdit() {
    gridThemeName.value = "";
    editingGridTheme.status = false;
    editingGridTheme.name = "";
    switchCreateThemeSectionLabels(false);
}

function getGridThemeFromStyleBlock(className, comparisonClassName) {
    let themeName = "";
    for (const theme of gridThemeList) {
        if (`.${theme} ${comparisonClassName}` === className) {
            themeName = theme;
            break;
        }
    }
    return themeName;
}

function switchCreateThemeSectionLabels(isUnderEdit) {
    const title = createGridThemeSection.querySelector("h2");
    if (isUnderEdit) {
        title.textContent = "Update Grid Theme";
        gridThemeClear.textContent = "Cancel";
        gridThemeSave.textContent = "Update";
    } else {
        title.textContent = "Create Grid Theme";
        gridThemeClear.textContent = "Clear";
        gridThemeSave.textContent = "Create Theme";
    }
}

function createGridThemeUI(name, isDefault) {
    const themeNode = parser.parseFromString(getGridThemeNode(utils.generateUniqueId()), "text/html");
    const themeLabel = themeNode.querySelector(".grid-theme-label");
    const editTheme = themeNode.querySelector(".grid-theme-edit");
    const deleteTheme = themeNode.querySelector(".grid-theme-delete");
    const defaultSwitch = themeNode.querySelector(".grid-theme-default");
    themeLabel.textContent = name;
    themeNode.body.firstChild.setAttribute("data-custom-grid-theme", name);

    if (isDefault) {
        defaultSwitch.checked = true;
    }

    defaultSwitch.addEventListener("change", (e) => {
        if (e.target.checked) {
            state.setUnsavedChanges(true);
            state.updateSettingsData("gridThemes.defaultTheme", name);
        }
    });

    // editTheme.addEventListener("click", (e) => {
    //     editingGridTheme.status = true;
    //     editingGridTheme.name = name;
    //     gridThemeName.value = name;
    //     switchCreateThemeSectionLabels(true);
    //     createGridThemeSection.scrollIntoView({ behavior: "smooth", block: "center" });
    // });

    deleteTheme.addEventListener("click", (e) => {
        state.setUnsavedChanges(true);
        clearGridThemeEdit();
        addOrRemoveThemeFromScope(name, "remove");
        document.querySelector(`[data-custom-grid-theme="${name}"]`).remove();

        gridThemeList.splice(0, gridThemeList.length, ...gridThemeList.filter((theme) => {
            return theme !== name;
        }));

        // Remove all styles defined under deleted theme
        stylesUI.updateStyleDefinitions(null, null, name, null);

        if (state.getSettingsData()["gridThemes.defaultTheme"] === name) {
            state.updateSettingsData("gridThemes.defaultTheme", null);
        }

        if (!gridThemeList.length) {
            state.updateSettingsData("gridThemes.themes", null);
            // state.updateStylesData(chartContainerClass, chartContainerStyles);
            savedGridThemesSection.classList.remove("visible");
        } else {
            state.updateSettingsData("gridThemes.themes", gridThemeList);
        }
    });

    document.querySelector(".grid-theme-list").prepend(themeNode.body.firstChild);
}

gridThemeClear.addEventListener("click", (e) => {
    clearGridThemeEdit();
});

gridThemeSave.addEventListener("click", (e) => {
    const name = gridThemeName.value;
    // const isValidName = utils.checkNameValidity(name, gridThemeList, editingGridTheme.name);
    const isValidName = utils.checkNameValidity(name, gridThemeList, "");
    if (!isValidName.valid) {
        alert(isValidName.reason);
        return;
    }

    gridThemeName.value = "";
    state.setUnsavedChanges(true);

    // Check if editing existing theme or adding new theme
    // if (editingGridTheme.status) {
    //     // Remove outdated theme data
    //     gridThemeList.splice(0, gridThemeList.length, ...gridThemeList.filter(theme => {
    //         return theme !== editingGridTheme.name;
    //     }));
    //     document.querySelector(`[data-custom-grid-theme="${editingGridTheme.name}"]`).remove();

    //     // Add latest theme data
    //     gridThemeList.push(name);
    //     createGridThemeUI(name, state.getSettingsData()["gridThemes.defaultTheme"] === editingGridTheme.name);
    //     if (state.getSettingsData()["gridThemes.defaultTheme"] === editingGridTheme.name) {
    //         state.updateSettingsData("gridThemes.defaultTheme", name);
    //     }
    //     editingGridTheme.status = false;
    //     editingGridTheme.name = "";
    //     switchCreateThemeSectionLabels(false);
    // } else {
        gridThemeList.push(name);
        createGridThemeUI(name, false);
        if (!savedGridThemesSection.classList.contains("visible")) {
            savedGridThemesSection.classList.add("visible");
        }
    // }
    state.updateSettingsData("gridThemes.themes", gridThemeList);
    alert("Grid theme created successfully. You can customize it in the Styles tab.");
    // Scroll the newly added/edited theme into the view
    savedGridThemesSection.querySelector(".saved-grid-theme").scrollIntoView({ behavior: "smooth", block: "center" });
});

export {
    savedGridThemesSection,
    getGridThemeList,
    getGridThemeFromStyleBlock,
    addThemeToList,
    addOrRemoveThemeFromScope,
    emptyThemeOptions,
    createGridThemeUI
};
