import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { SettingsMenu, SettingsMenuIcons } from "../data/formEnums";
import { world } from "@minecraft/server";
import { SettingsHandler } from "../handlers/settings";
// Cooldown tracking for settings menu access
const settingsMenuCooldowns = new Map();
const SETTINGS_MENU_COOLDOWN_MS = 1000; // 1 second cooldown
export function openSettingsMenuMain(player) {
    // Check cooldown to prevent double-opening
    const now = Date.now();
    const lastOpened = settingsMenuCooldowns.get(player.name) || 0;
    if (now - lastOpened < SETTINGS_MENU_COOLDOWN_MS) {
        return;
    }
    // Check if player is whitelisted to access settings
    // Allow access if no one is whitelisted yet (first time setup) or if player is whitelisted
    const whitelist = SettingsHandler.getWhitelist();
    if (whitelist.length > 0 && !SettingsHandler.isWhitelisted(player.name)) {
        player.sendMessage(SettingsMenu.NoPermissionMessage);
        return;
    }
    // If this is the first time and no one is whitelisted, auto-add the player
    if (whitelist.length === 0) {
        SettingsHandler.addWhitelist(player.name);
        player.sendMessage(SettingsMenu.AutoWhitelistMessage);
    }
    // Update cooldown timestamp only when menu actually opens
    settingsMenuCooldowns.set(player.name, now);
    const form = new ActionFormData();
    form.title(SettingsMenu.MainTitle);
    form.body(SettingsMenu.MainBody);
    form.button(SettingsMenu.WhitelistButton, SettingsMenuIcons.Whitelist);
    form.button(SettingsMenu.SpongeConfigurationButton, SettingsMenuIcons.SpongeConfiguration);
    form.button(SettingsMenu.ExitButton, SettingsMenuIcons.Exit);
    form.show(player).then((response) => {
        if (response.canceled || response.selection === undefined)
            return;
        switch (response.selection) {
            case 0:
                openSettingsMenuWhitelist(player);
                break;
            case 1:
                openSettingsMenuSponge(player);
                break;
            case 2:
                // Exit - do nothing
                break;
        }
    });
}
export function openSettingsMenuWhitelist(player) {
    const form = new ActionFormData();
    form.title(SettingsMenu.WhitelistTitle);
    form.body(SettingsMenu.WhitelistBody);
    form.button(SettingsMenu.ResetWhitelistButton, SettingsMenuIcons.ResetWhitelist);
    form.button(SettingsMenu.AddPlayerButton, SettingsMenuIcons.AddPlayer);
    form.button(SettingsMenu.RemovePlayerButton, SettingsMenuIcons.RemovePlayer);
    form.button(SettingsMenu.BackButton, SettingsMenuIcons.Exit);
    form.show(player).then((response) => {
        if (response.canceled || response.selection === undefined)
            return;
        switch (response.selection) {
            case 0:
                openConfirmResetWhitelist(player);
                break;
            case 1:
                openAddPlayerForm(player);
                break;
            case 2:
                openRemovePlayerForm(player);
                break;
            case 3:
                openSettingsMenuMain(player);
                break;
        }
    });
}
export function openConfirmResetWhitelist(player) {
    const form = new ActionFormData();
    form.title(SettingsMenu.ResetWhitelistTitle);
    form.body(SettingsMenu.ResetWhitelistBody);
    form.button(SettingsMenu.YesResetButton, SettingsMenuIcons.Yes);
    form.button(SettingsMenu.NoBackButton, SettingsMenuIcons.Exit);
    form.show(player).then((response) => {
        if (response.canceled || response.selection === undefined) {
            openSettingsMenuWhitelist(player);
            return;
        }
        switch (response.selection) {
            case 0:
                SettingsHandler.resetWhitelist();
                player.sendMessage(SettingsMenu.WhitelistResetMessage);
                openSettingsMenuWhitelist(player);
                break;
            case 1:
                openSettingsMenuWhitelist(player);
                break;
        }
    });
}
export function openAddPlayerForm(player) {
    const form = new ModalFormData();
    form.title(SettingsMenu.AddPlayerTitle);
    // Get all online players
    const allOnlinePlayers = world.getAllPlayers().map(p => p.name);
    if (allOnlinePlayers.length === 0) {
        player.sendMessage(SettingsMenu.NoPlayersOnlineMessage);
        openSettingsMenuWhitelist(player);
        return;
    }
    // Filter out players who are already whitelisted
    const availablePlayers = allOnlinePlayers.filter(playerName => !SettingsHandler.isWhitelisted(playerName));
    if (availablePlayers.length === 0) {
        player.sendMessage(SettingsMenu.AllPlayersWhitelistedMessage);
        return;
    }
    form.dropdown(SettingsMenu.AddPlayerDropdown, availablePlayers);
    form.show(player).then((response) => {
        if (response.canceled || !response.formValues) {
            openSettingsMenuWhitelist(player);
            return;
        }
        const selectedPlayerIndex = response.formValues[0];
        const selectedPlayerName = availablePlayers[selectedPlayerIndex];
        // Double-check they're not already whitelisted (shouldn't happen but safety check)
        if (SettingsHandler.isWhitelisted(selectedPlayerName)) {
            player.sendMessage(SettingsMenu.PlayerAlreadyWhitelistedMessage.replace("{player}", selectedPlayerName));
        }
        else {
            SettingsHandler.addWhitelist(selectedPlayerName);
            player.sendMessage(SettingsMenu.PlayerAddedMessage.replace("{player}", selectedPlayerName));
        }
        openSettingsMenuWhitelist(player);
    });
}
export function openRemovePlayerForm(player) {
    const form = new ModalFormData();
    form.title(SettingsMenu.RemovePlayerTitle);
    // Get current whitelist
    const whitelistedPlayers = SettingsHandler.getWhitelist();
    if (whitelistedPlayers.length === 0) {
        player.sendMessage(SettingsMenu.NoPlayersWhitelistedMessage);
        return;
    }
    form.dropdown(SettingsMenu.RemovePlayerDropdown, whitelistedPlayers);
    form.show(player).then((response) => {
        if (response.canceled || !response.formValues) {
            return;
        }
        const selectedPlayerIndex = response.formValues[0];
        const selectedPlayerName = whitelistedPlayers[selectedPlayerIndex];
        SettingsHandler.removeWhitelist(selectedPlayerName);
        player.sendMessage(SettingsMenu.PlayerRemovedMessage.replace("{player}", selectedPlayerName));
        openSettingsMenuWhitelist(player);
    });
}
export function openSettingsMenuSponge(player) {
    const form = new ModalFormData();
    form.title(SettingsMenu.SpongeConfigurationTitle);
    // Get current sponge states
    const spongeStates = SettingsHandler.getAllSpongeToggleStates();
    // Create toggles for all sponges
    const spongeKeys = Object.keys(spongeStates);
    // Add toggles for each sponge with friendly names
    const spongeDisplayNames = {
        antiEnderSponge: "Anti-Ender Sponge",
        clearWeatherSponge: "Clear Weather Sponge",
        decaySponge: "Decay Sponge",
        effectsSponge: "Effects Sponge",
        explosionSponge: "Explosion Sponge",
        feedingSponge: "Feeding Sponge",
        fireSponge: "Fire Sponge",
        frostSponge: "Frost Sponge",
        gravitySponge: "Gravity Sponge",
        growthSponge: "Growth Sponge",
        healingSponge: "Healing Sponge",
        jumpSponge: "Jump Sponge",
        lavaSponge: "Lava Sponge",
        lightSponge: "Light Sponge",
        magnetSponge: "Magnet Sponge",
        nightSponge: "Night Sponge",
        nightVisionSponge: "Night Vision Sponge",
        poisonSponge: "Poison Sponge",
        redstoneSponge: "Redstone Sponge",
        shadowSponge: "Shadow Sponge",
        silkSponge: "Silk Sponge",
        smokeSponge: "Smoke Sponge",
        speedSponge: "Speed Sponge",
        stickySponge: "Sticky Sponge",
        teleportSponge: "Teleport Sponge",
        thornSponge: "Thorn Sponge",
        tntSponge: "TNT Sponge",
        voidSponge: "Void Sponge",
        witherSponge: "Wither Sponge",
        xpSponge: "XP Sponge"
    };
    // Sort sponges alphabetically by display name
    const sortedSpongeKeys = spongeKeys.sort((a, b) => spongeDisplayNames[a].localeCompare(spongeDisplayNames[b]));
    sortedSpongeKeys.forEach(key => {
        form.toggle(spongeDisplayNames[key], spongeStates[key]);
    });
    form.show(player).then((response) => {
        if (response.canceled || !response.formValues) {
            openSettingsMenuMain(player);
            return;
        }
        // Update sponge settings based on form responses
        let changesCount = 0;
        sortedSpongeKeys.forEach((key, index) => {
            const newValue = response.formValues[index];
            const currentValue = spongeStates[key];
            if (newValue !== currentValue) {
                SettingsHandler.toggleSponge(key);
                changesCount++;
            }
        });
        if (changesCount > 0) {
            player.sendMessage(SettingsMenu.SpongeSettingsUpdatedMessage.replace("{count}", changesCount.toString()));
        }
        else {
            player.sendMessage(SettingsMenu.NoChangesMessage);
        }
        openSettingsMenuMain(player);
    });
}
