import * as utils from "../utility/helper-functions.js";
import * as state from "../state/state.js";

const parser = new DOMParser();
const fontName = document.querySelector(".font-name");
// const fontFile = document.querySelector(".font-file");
// const fontUpload = document.querySelector(".font-upload");
const fontFileName = document.querySelector(".font-file-name");
const fontClear = document.querySelector(".clear-font");
const fontSave = document.querySelector(".save-font");
const createFontSection = document.querySelector(".upload-font-section");
const savedFontsSection = document.querySelector(".saved-fonts-section");
const chartContainerClass = ".vitara-theme-custom.vitara-chart-container";
// let fontUploadData = [];
let fontDeleteData = [];

const fontList = [];
const editingFont = {
    status: false,
    name: ""
};

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

function getFontList() {
    return fontList;
}

function addFontToList(value) {
    if (Array.isArray(value)) {
        // Array of fonts
        fontList.push(...value);
    } else {
        // Single font
        fontList.push(value);
    }
}

function clearFontEdit() {
    fontName.value = "";
    fontFileName.value = "";
    editingFont.status = false;
    editingFont.name = "";
    switchFontSectionLabels(false);
}

function switchFontSectionLabels(isUnderEdit) {
    const title = createFontSection.querySelector("h2");
    if (isUnderEdit) {
        title.textContent = "Update Font";
        fontClear.textContent = "Cancel";
        fontSave.textContent = "Update";
    } else {
        title.textContent = "Add New Font";
        fontClear.textContent = "Clear";
        fontSave.textContent = "Add Font";
    }
}

function createCustomFontsUI(name, isDefault) {
    const fontNode = parser.parseFromString(getFontNodeSrc(utils.generateUniqueId()), "text/html");
    const fontLabel = fontNode.querySelector(".custom-font-label");
    const editFont = fontNode.querySelector(".font-edit");
    const deleteFont = fontNode.querySelector(".font-delete");
    const defaultSwitch = fontNode.querySelector(".font-default");
    fontLabel.textContent = name;
    fontNode.body.firstChild.setAttribute("data-custom-font", name);

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

    defaultSwitch.addEventListener("change", (e) => {
        if (e.target.checked) {
            state.setUnsavedChanges(true);
            state.updateSettingsData("font.defaultFont", name);
            state.updateSettingsData("font.customFonts", fontList);
            state.updateStylesData(chartContainerClass, {
                ...state.getStylesData()[chartContainerClass],
                "font-family": utils.generateFontFamilyString(fontList, name)
            });
        }
    });

    editFont.addEventListener("click", (e) => {
        editingFont.status = true;
        editingFont.name = name;
        fontName.value = name;
        const fontFaceString = state.getFontFaceDefinitions().find((definition) => definition.includes(name)) || "";
        const fontFileMatch = fontFaceString.match(/src\s*:\s*url\(['"]?([^'")]+)['"]?\)/);
        const fileName = fontFileMatch ? fontFileMatch[1].split("fonts/")[1] : null;
        fontFileName.value = fileName || "";
        switchFontSectionLabels(true);
        createFontSection.scrollIntoView({ behavior: "smooth", block: "center" });
    });

    deleteFont.addEventListener("click", (e) => {
        state.setUnsavedChanges(true);
        clearFontEdit();
        // const isUnsavedFont = fontUploadData.find(fontInfo => fontInfo.fontName === name);
        // if (isUnsavedFont) {
        //     fontUploadData.filter(fontInfo => fontInfo.fontName !== name);
        // } else {
        //     fontDeleteData.push(state.getSettingsData()[`font.${name}`]);
        // }

        state.removeFontFaceDefinition(name);
        document.querySelector(`[data-custom-font="${name}"]`).remove();
        // state.updateSettingsData(`font.${name}`, null);

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

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

        if (!fontList.length) {
            state.updateSettingsData("font.customFonts", null);
            const chartContainerStyles = state.getStylesData()[chartContainerClass];
            delete chartContainerStyles["font-family"];
            state.updateStylesData(chartContainerClass, chartContainerStyles);
            if (Object.keys(state.getStylesData()[chartContainerClass]).length === 0) {
                state.updateStylesData(chartContainerClass, null);
            }
            savedFontsSection.classList.remove("visible");
        } else {
            state.updateSettingsData("font.customFonts", fontList);
            state.updateStylesData(chartContainerClass, {
                ...state.getStylesData()[chartContainerClass],
                "font-family": utils.generateFontFamilyString(fontList, state.getSettingsData()["font.defaultFont"])
            });
        }
    });

    document.querySelector(".font-list").prepend(fontNode.body.firstChild);
}

// fontUpload.addEventListener("click", (e) => {
//     const file = fontFile.files[0];
//     const name = fontName.value.trim();

//     if (!file) {
//         alert("No file uploaded");
//         return;
//     }

//     if (!name) {
//         alert("Font family name required");
//         return;
//     }

//     fontUploadData.push({
//         fontName: name,
//         fontFile: file,
//         fileName: file.name
//     });

//     // Clean-up inputs and create new custom font's UI
//     fontFile.value = "";
//     fontName.value = "";
//     fontList.push(name);
//     createCustomFontsUI(name, false);
//     state.setUnsavedChanges(true);

//     if (!savedFontsSection.classList.contains("visible")) {
//         savedFontsSection.classList.add("visible");
//     }

//     // Update data collections
    // state.addFontFaceDefinition(`@font-face { font-family: '${name}'; src: url('./fonts/${file.name}'); }`);
    // state.updateSettingsData(chartContainerClass, {
    //     ...state.getStylesData()[chartContainerClass],
    //     "font-family": utils.generateFontFamilyString(fontList, state.getSettingsData()["font.defaultFont"]),
    // });
//     stylesData[chartContainerClass]["font-family"] = utils.generateFontFamilyString(fontList, state.getSettingsData()["font.defaultFont"]);
//     state.updateSettingsData(`font.${name}`, file.name);
//     state.updateSettingsData("font.customFonts", fontList);
// });

fontClear.addEventListener("click", (e) => {
    clearFontEdit();
});

fontSave.addEventListener("click", (e) => {
    const name = fontName.value;
    const file = fontFileName.value.trim();

    const isValidName = utils.checkNameValidity(name, fontList, editingFont.name);
    if (!isValidName.valid) {
        alert(isValidName.reason);
        return;
    }

    function addAndUpdateFont() {
        fontName.value = "";
        fontFileName.value = "";
        state.setUnsavedChanges(true);

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

            // Add latest font data
            fontList.push(name);
            createCustomFontsUI(name, state.getSettingsData()["font.defaultFont"] === editingFont.name);
            if (state.getSettingsData()["font.defaultFont"] === editingFont.name) {
                state.updateSettingsData("font.defaultFont", name);
            }

            editingFont.status = false;
            editingFont.name = "";
            switchFontSectionLabels(false);
        } else {
            fontList.push(name);
            createCustomFontsUI(name, false);
            if (!savedFontsSection.classList.contains("visible")) {
                savedFontsSection.classList.add("visible");
            }
        }
        state.updateStylesData(chartContainerClass, {
            ...state.getStylesData()[chartContainerClass],
            "font-family": utils.generateFontFamilyString(fontList, state.getSettingsData()["font.defaultFont"])
        });
        // state.updateSettingsData(`font.${name}`, file);
        state.updateSettingsData("font.customFonts", fontList);
        // Scroll the newly added/edited font into the view
        savedFontsSection.querySelector(".saved-font").scrollIntoView({ behavior: "smooth", block: "center" });
    }

    if (!file) {
        const saveGenericFont = confirm("No font file provided. Add this as a system-dependent font family instead?");
        if (saveGenericFont) {
            addAndUpdateFont();
        }
        return;
    }

    utils.checkFileExists(`../custom/fonts/${file}`).then(exists => {
        if (exists) {
            addAndUpdateFont();
            state.addFontFaceDefinition(`@font-face { font-family: '${name}'; src: url('./fonts/${file}'); }`);
        } else {
            alert("File not found. Please check that the file name is correct (with extension included) and placed under 'custom/fonts' folder.");
            return;
        }
    });
});

export {
    savedFontsSection,
    getFontList,
    addFontToList,
    createCustomFontsUI
};
