import { world } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { getOrCreateScoreboard } from "./util/scoreboard.js";

// Setup scoreboard
const settingsScoreboard = getOrCreateScoreboard("SD_realism_settings");

// Constants
// Categories
const categories = {
    blocks: {
        icon: "textures/squaredreams/realism/icons/blocks",
        settings: ["custom_blocks"]
    },
    water: {
        icon: "textures/squaredreams/realism/icons/water",
        settings: ["splashes", "water_cascades"]
    },
    particles: {
        icon: "textures/squaredreams/realism/icons/particles",
        settings: ["dust", "sandstorm", "falling_leaves", "fog"]
    },
    weather: {
        icon: "textures/squaredreams/realism/icons/weather",
        settings: ["lens_flare", "godrays", "volumetric_clouds", "custom_fog", "snow"]
    },
    sounds: {
        icon: "textures/squaredreams/realism/icons/sounds",
        settings: ["ambient_sounds"]
    },
    animals: {
        icon: "textures/squaredreams/realism/icons/insects_animals",
        settings: ["fireflies", "butterflies", "birds"]
    },
    Lighting: {
        icon: "textures/squaredreams/realism/icons/lighting",
        settings: ["dynamic_lighting"]
    }
};

// Set all settings to active by default
initializeDefaultValues();

// Item listener will open the menu
world.afterEvents.itemUse.subscribe(event => {
    if (event.itemStack.typeId === "squaredreams_realism:menu") {
        showMenu(event.source);
    }
});

// Set all settings to active by default
function initializeDefaultValues() {
    for (const category of Object.values(categories)) {
        for (const setting of category.settings) {
            if (!settingsScoreboard.hasParticipant(setting)) {
                settingsScoreboard.setScore(setting, setting === "water_cascades" || setting === "custom_blocks" ? 2 : 1); // Set default for water_cascades and custom_blocks
            }
        }
    }
}

// Menu opener
export function showMenu(player) {
    const form = new ActionFormData();
    // Title
    form.title({ rawtext: [{ translate: "ui.squaredreams_realism.settings.title" }] });

    // Add all categories
    for (const [categoryID, category] of Object.entries(categories)) {
        form.button({ rawtext: [{ translate: `ui.squaredreams_realism.settings.category.${categoryID}` }] }, category.icon);
    }

    // Failsafe
    form.show(player).then(response => {
        if (!response.canceled) {
            const chosenCategory = Object.keys(categories)[response.selection];
            if (chosenCategory) {
                showCategoryMenu(chosenCategory, player);
            }
        }
    });
}

// Category pages
function showCategoryMenu(categoryID, player) {
    const category = categories[categoryID];
    const form = new ModalFormData();
    // Title
    form.title({
        rawtext: [
            { translate: `ui.squaredreams_realism.settings.category.${categoryID}` },
            { text: " - " },
            { translate: "ui.squaredreams_realism.settings.page_text" }
        ]
    });
    form.submitButton({ rawtext: [{ translate: "ui.squaredreams_realism.settings.submit_button" }] })

    // Create all toggles and sliders
    for (const setting of category.settings) {
        if (setting === "water_cascades" || setting === "custom_blocks") {
            const value = settingsScoreboard.getScore(setting);
            form.dropdown({ rawtext: [{ translate: `ui.squaredreams_realism.settings.setting.${setting}` }] }, ["OFF", "Low", "Medium", "High"], value);
        } else {
            const value = settingsScoreboard.getScore(setting) !== 0;
            form.toggle({ rawtext: [{ translate: `ui.squaredreams_realism.settings.setting.${setting}` }] }, value);
        }
    }

    // Failsafe
    form.show(player).then(response => {
        if (!response.canceled && response.formValues) {
            updateSettings(categoryID, response.formValues);
            showMenu(player);
        }
    });
}

// Updates scoreboard value based on toggle setting
function updateSettings(categoryID, formValues) {
    const settings = categories[categoryID].settings;
    let settingsChanged = false;

    settings.forEach((setting, index) => {
        // Check if the setting has changed
        if (settingsScoreboard.getScore(setting) != formValues[index]) {
            settingsChanged = true;
        }

        // Update the settings
        if (setting === "water_cascades" || setting === "custom_blocks") {
            // Store the index of the selected slider option (0 for "OFF", 1 for "Low", 2 for "Medium", 3 for "High")
            settingsScoreboard.setScore(setting, formValues[index]);
        } else {
            settingsScoreboard.setScore(setting, formValues[index] ? 1 : 0);
        }
    });

    if (settingsChanged) {
        world.sendMessage({rawtext: [{translate: "text.squaredreams_realism.settings_saved"}]});
    }
}

// Function to grab the data in the VFX scripts
export function settingEnabled(setting) {
    return settingsScoreboard.getScore(setting);
}