import { world, system, CommandPermissionLevel, CustomCommandParamType, CustomCommandStatus, ItemStack } from "@minecraft/server";
import { ActionFormData, ModalFormData, MessageFormData } from "@minecraft/server-ui";

export const openChestCommand = {
    options: {
        name: "sv:oc",
        description: "Admin container manager with persistent toggle and focus fix.",
        permissionLevel: CommandPermissionLevel.Admin,
        cheatsRequired: false,
        mandatoryParameters: [
            { name: "mode", type: CustomCommandParamType.String } 
        ],
        optionalParameters: [
            { name: "location", type: CustomCommandParamType.Location }
        ]
    },
    callback: (origin, mode, location) => {
        const player = origin.sourceEntity;
        if (!player) return { status: CustomCommandStatus.Failure, message: "Players only." };

        let x, y, z;
        const lowerMode = mode.toLowerCase();

        if (lowerMode === "f") {
            const lookAt = player.getBlockFromViewDirection({ maxDistance: 15 });
            if (!lookAt) return { status: CustomCommandStatus.Failure, message: "§cNo block in sight." };
            x = lookAt.block.location.x;
            y = lookAt.block.location.y;
            z = lookAt.block.location.z;
        } 
        else if (lowerMode === "c") {
            if (!location) return { status: CustomCommandStatus.Failure, message: "§cUsage: /sv:oc c <x> <y> <z>" };
            x = location.x;
            y = location.y;
            z = location.z;
        }
        else {
            return { status: CustomCommandStatus.Failure, message: "§cUse 'f' or 'c'." };
        }

        const block = player.dimension.getBlock({ x, y, z });
        const container = block?.getComponent("inventory")?.container;
        if (!container) return { status: CustomCommandStatus.Failure, message: "§cInvalid container." };

        const maxSlots = container.size;

        // --- MAIN MENU ---
        const runMainMenu = () => {
            // Focus Fix: Ensure the previous UI is fully cleared before showing next
            system.run(() => {
                const main = new ActionFormData();
                main.title(`Manage: ${block.typeId.split(":")[1]}`);
                main.button("§l+§r Add Items List");
                main.button("§l-§r Delete Items List");
                main.button("§c§lEXIT MENU");

                main.show(player).then(res => {
                    if (res.canceled || res.selection === 2) return;
                    if (res.selection === 0) runAddMenu([], false); // Default toggle off first time
                    if (res.selection === 1) runDeleteMenu([]);
                });
            });
        };

        // --- ADD MENU ---
        // Added 'currentToggle' as a parameter to remember the state
        const runAddMenu = (stagedAdditions = [], currentToggle = false, errorMessage = "") => {
            system.run(() => {
                const modal = new ModalFormData();
                modal.title("Add Items (List Mode)");

                let listText = stagedAdditions.length === 0 
                    ? "§8(List is empty)§r" 
                    : stagedAdditions.map((i, idx) => `§a${idx+1}. ${i.id} (x${i.amt}) Slot ${i.slot}`).join("\n");
                
                let header = errorMessage !== "" ? `${errorMessage}\n\n` : "";
                modal.label(`${header}§e§lPENDING ADDITIONS:§r\n${listText}\n\n§b§lTUTORIAL:§r §7To put spaces, use §f_ §7(Example: §fnetherite_ingot§7).`);

                // Set defaultValue to 'currentToggle' so it stays ON if you turned it ON
                modal.toggle("Use Player Inventory?", { defaultValue: currentToggle }); 
                modal.textField("Item ID", "diamond", { defaultValue: "" });    
                modal.textField("Amount", "64", { defaultValue: "64" });        
                modal.textField("Slot", "0", { defaultValue: "" });            

                modal.show(player).then(res => {
                    if (res.canceled) return runMainMenu();
                    
                    const [_, useInv, id, amtStr, slotStr] = res.formValues;
                    const amt = parseInt(amtStr) || 1;
                    const slotNum = parseInt(slotStr);

                    if (slotNum >= maxSlots) {
                        return runAddMenu(stagedAdditions, useInv, `§cMax Slot is ${maxSlots - 1}!`);
                    }

                    if (id && id.trim() !== "") {
                        const fullId = id.includes(":") ? id : `minecraft:${id}`;
                        
                        if (useInv) {
                            let count = 0;
                            const pInv = player.getComponent("inventory").container;
                            for (let i = 0; i < pInv.size; i++) {
                                const itm = pInv.getItem(i);
                                if (itm?.typeId === fullId) count += itm.amount;
                            }

                            if (count < amt) {
                                return runAddMenu(stagedAdditions, useInv, `§cYou don't have enough ${id.replace(/_/g, " ")}!`);
                            }
                            
                            let remaining = amt;
                            for (let i = 0; i < pInv.size; i++) {
                                const itm = pInv.getItem(i);
                                if (itm?.typeId === fullId) {
                                    const take = Math.min(itm.amount, remaining);
                                    if (itm.amount === take) pInv.setItem(i, undefined);
                                    else pInv.setItem(i, new ItemStack(itm.typeId, itm.amount - take));
                                    remaining -= take;
                                    if (remaining <= 0) break;
                                }
                            }
                        }

                        const newItem = { id: fullId, amt: amt, slot: isNaN(slotNum) ? 0 : slotNum };
                        const itemAtSlot = container.getItem(newItem.slot);
                        
                        if (itemAtSlot) {
                            const existingName = itemAtSlot.typeId.split(":")[1].replace(/_/g, " ");
                            const warn = new MessageFormData();
                            warn.title("§6Slot Occupied!");
                            warn.body(`§7Slot §f${newItem.slot} §7is occupied by:\n§e§l${existingName} (x${itemAtSlot.amount})§r\n\n§fOverwrite this item?`);
                            warn.button2("§lYES");
                            warn.button1("§lNO");

                            warn.show(player).then(wRes => {
                                if (wRes.selection === 1) stagedAdditions.push(newItem);
                                // Pass 'useInv' back so the toggle stays the same
                                runAddMenu(stagedAdditions, useInv);
                            });
                        } else {
                            stagedAdditions.push(newItem);
                            runAddMenu(stagedAdditions, useInv);
                        }
                    } 
                    else if (stagedAdditions.length > 0) {
                        stagedAdditions.forEach(i => {
                            try { container.setItem(i.slot, new ItemStack(i.id, i.amt)); } catch(e) {}
                        });
                        player.sendMessage(`§a[SV] Container updated.`);
                        runMainMenu(); 
                    } else {
                        runMainMenu();
                    }
                });
            });
        };

        // --- DELETE MENU (Focus fix included) ---
        const runDeleteMenu = (stagedDeletions = []) => {
            system.run(() => {
                const modal = new ModalFormData();
                modal.title("Delete Items");
                let listText = stagedDeletions.length === 0 ? "§8(List is empty)§r" : stagedDeletions.map((i, idx) => `§c${idx+1}. ${i.id}`).join("\n");
                modal.label(`§e§lPENDING DELETE:§r\n${listText}\n\n§7Esc/Back to return to Main Menu.`);
                modal.toggle("§cList All Container Contents?", { defaultValue: false });
                modal.textField("Item ID to Delete", "apple", { defaultValue: "" });

                modal.show(player).then(res => {
                    if (res.canceled) return runMainMenu();
                    const [_, autoFill, id] = res.formValues;
                    if (autoFill) {
                        let newList = [];
                        for (let i = 0; i < container.size; i++) {
                            const itm = container.getItem(i);
                            if (itm) newList.push({ id: itm.typeId });
                        }
                        return runDeleteMenu(newList);
                    }
                    if (id && id.trim() !== "") {
                        stagedDeletions.push({ id: id.includes(":") ? id : `minecraft:${id}` });
                        runDeleteMenu(stagedDeletions);
                    } else if (stagedDeletions.length > 0) {
                        stagedDeletions.forEach(del => {
                            for (let i = 0; i < container.size; i++) {
                                if (container.getItem(i)?.typeId === del.id) container.setItem(i, undefined);
                            }
                        });
                        player.sendMessage("§a[SV] Items cleared.");
                        runMainMenu();
                    } else {
                        runMainMenu();
                    }
                });
            });
        };

        // Initial launch inside system.run to solve the "invisible UI" bug
        system.run(() => runMainMenu());
        return { status: CustomCommandStatus.Success };
    }
};

