import { world, system, BlockPermutation, Player, ItemStack } from "@minecraft/server";
import { ActionFormData, ModalFormData, MessageFormData, uiManager } from "@minecraft/server-ui";
function showSettingsForm(player) {
    const times = ["30s", "2min", "3min", "5min", "10min", "15min"];
    const scopes = ["To all online players", "To no one", "To players within 100 blocks"];
    const animation = ["Risen", "Slow Awakening", "Superman", "Happy Dance", "Thank You", "Flip"];
    const particle = ["Totem", "Halo"];
    const revival = ["Instant", "5s", "10s", "15s", "30s", "1min"];
    const materials = [
        "Coal", "Lapis Lazuli", "Redstone", "Copper", "Iron Ingot", "Gold Ingot", "Diamond", "Emerald", "Netherite Scrap", "Netherite", "Enchanted Golden Apple", "Totem Of Undying"
    ];
    const beacontype = [
        "Red", "Green", "Blue", "Yellow", "Pink"
    ];

    function getSavedValues() {
        return {
            savedTime: world.getDynamicProperty("revive_time") || "30s",
            savedCoords: world.getDynamicProperty("revive_coordinates") ?? true,
            reviveCost: world.getDynamicProperty("revive_cost") ?? false,
            savedMaterial: world.getDynamicProperty("revive_cost_material") || "Coal",
            savedQuantity: Number(world.getDynamicProperty("revive_cost_quantity")) || 1,
            savedActionbar: world.getDynamicProperty("revive_actionbar") || "To players within 100 blocks",
            savedAnimation: world.getDynamicProperty("revive_animation") || "Risen",
            savedParticle: world.getDynamicProperty("revive_particle") || "Halo",
            savedRevival: world.getDynamicProperty("revival_time") || "5s",
            savedBeacon: world.getDynamicProperty("death_beacon") ?? true,
            savedBeaconType: world.getDynamicProperty("beacon_type") || "Red",
        };
    }

    const mainForm = new ActionFormData()
        .title("Revive Settings")
        .body("Customize the Revive Add-On by adjusting the time it takes before a player dies, notifications, a cost and more!")
        .button("Customization", "textures/cbcl/rm/icons/settings_icon")
        .button("Revive Cost", "textures/items/totem")
        .button("Death Beacon", "textures/blocks/beacon");

    mainForm.show(player).then((response) => {
        if (response.canceled) return;

        const {
            savedTime,
            savedCoords,
            reviveCost,
            savedMaterial,
            savedQuantity,
            savedActionbar,
            savedAnimation,
            savedParticle,
            savedRevival,
            savedBeacon,
            savedBeaconType
        } = getSavedValues();

        if (response.selection === 0) {
            // Customization podforma
            const customizationForm = new ModalFormData()
                .title("Revive Settings")
                .dropdown("Time to revive", times, {
                    defaultValueIndex: times.indexOf(savedTime) !== -1 ? times.indexOf(savedTime) : 0,
                    tooltip: "The amount of time before a player actually dies."
                })
                .toggle("Coordinates in chat death message", {
                    defaultValue: savedCoords,
                    tooltip: "Disable if you want to keep your coordinates private."
                })
                .dropdown("Show revival actionbar", scopes, {
                    defaultValueIndex: scopes.indexOf(savedActionbar) !== -1 ? scopes.indexOf(savedActionbar) : 0
                })
                .dropdown("Resurrection animation", animation, {
                    defaultValueIndex: animation.indexOf(savedAnimation) !== -1 ? animation.indexOf(savedAnimation) : 0
                })
                .dropdown("Revival time", revival, {
                    defaultValueIndex: revival.indexOf(savedRevival) !== -1 ? revival.indexOf(savedRevival) : 0,
                    tooltip: "Time it takes to revive a player."
                })
                .dropdown("Resurrection particle", particle, {
                    defaultValueIndex: particle.indexOf(savedParticle) !== -1 ? particle.indexOf(savedParticle) : 0
                })
                .submitButton("Save");

            customizationForm.show(player).then((resp) => {
                if (resp.canceled) return;
                const [newTimeIndex, coordsEnabled, newActionbarIndex, newAnimationIndex, newRevivalIndex, newParticleIndex] = resp.formValues;

                world.setDynamicProperty("revive_time", times[newTimeIndex]);
                world.setDynamicProperty("revive_coordinates", coordsEnabled);
                world.setDynamicProperty("revive_actionbar", scopes[newActionbarIndex]);
                world.setDynamicProperty("revive_animation", animation[newAnimationIndex]);
                world.setDynamicProperty("revive_particle", particle[newParticleIndex]);
                world.setDynamicProperty("revival_time", revival[newRevivalIndex]);

                player.sendMessage("§aCustomization settings updated.");
            });
        } else if (response.selection === 1) {
            // Revive Cost podforma
            const costForm = new ModalFormData()
                .title("Revive Settings")
                .toggle("Revive cost", {
                    defaultValue: reviveCost,
                    tooltip: "Enable this if you want to charge players for reviving. If disabled, players can revive for free."
                })
                .dropdown("Cost Material", materials, {
                    defaultValueIndex: materials.indexOf(savedMaterial) !== -1 ? materials.indexOf(savedMaterial) : 0
                })
                .slider("Cost Quantity", 1, 256, {
                    defaultValue: savedQuantity
                })
                .submitButton("Save");

            costForm.show(player).then((resp) => {
                if (resp.canceled) return;
                const [reviveCostValue, costMaterialValue, costQuantityValue] = resp.formValues;

                world.setDynamicProperty("revive_cost", reviveCostValue);
                world.setDynamicProperty("revive_cost_material", materials[costMaterialValue]);
                world.setDynamicProperty("revive_cost_quantity", costQuantityValue);

                player.sendMessage("§aRevive cost settings updated.");
            });
        }
        else if (response.selection === 2) {
            // Beacon Form
            const beaconForm = new ModalFormData()
                .title("Revive Settings")
                .toggle("Death Beacon", {
                    defaultValue: savedBeacon,
                    tooltip: "Enable this if you want to have a death beacon"
                })
                .dropdown("Beacon Color", beacontype, {
                    defaultValueIndex: beacontype.indexOf(savedBeaconType) !== -1 ? beacontype.indexOf(savedBeaconType) : 0
                })
                .submitButton("Save");

            beaconForm.show(player).then((resp) => {
                if (resp.canceled) return;
                const [deathBeaconValue, beaconTypeValue] = resp.formValues;

                world.setDynamicProperty("death_beacon", deathBeaconValue);
                world.setDynamicProperty("beacon_type", beacontype[beaconTypeValue]);

                player.sendMessage("§aDeath beacon settings updated.");
            });
        }
    }).catch((err) => {
        console.warn("Error showing main form: " + err);
    });
}



world.afterEvents.itemUse.subscribe((event) => {
    if (event.itemStack.typeId === "cbcl_rm:revive_settings") {
        showSettingsForm(event.source);

    }
});