import { world, system, Player } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";

const SCOREBOARD_OBJECTIVE = "Money";

const getScore = (objective, target, useZero = true) => {
    try {
        const obj = world.scoreboard.getObjective(objective);
        if (!obj) return useZero ? 0 : NaN;
        if (typeof target === "string") {
            const participant = obj.getParticipants().find((v) => v.displayName === target);
            return participant ? obj.getScore(participant) : (useZero ? 0 : NaN);
        }
        return obj.getScore(target.scoreboard);
    } catch {
        return useZero ? 0 : NaN;
    }
};

export const moneyTransfer = (player) => {
    const players = [...world.getPlayers()];

    new ModalFormData()
        .title("§lMoney Transfer")
        .dropdown(
            "        Choose Who To Send Money!",
            players.map((p) => p.name)
        )
        .textField(
            `Enter The Amount You're Sending!\n§aYour Balance: §2$${getScore(SCOREBOARD_OBJECTIVE, player.name)}`,
            `§r§7Only Use Positive Numbers`
        )
        .show(player)
        .then(({ formValues: [dropdown, textField] }) => {
            const selectedPlayer = players[dropdown];

            if (selectedPlayer.name === player.name) {
                player.sendMessage("§cYou can't select yourself");
                player.playSound("note.bass");
                return;
            }

            if (textField.includes("-") || isNaN(Number(textField)) || Number(textField) <= 0) {
                player.sendMessage("§cOnly use positive numbers");
                player.playSound("note.bass");
                return;
            }

            const amount = Math.floor(Number(textField));
            const playerBalance = getScore(SCOREBOARD_OBJECTIVE, player.name);

            if (playerBalance < amount) {
                player.sendMessage("§cYou don't have enough Money");
                player.playSound("note.bass");
                return;
            }

            try {
                player.runCommandAsync(`scoreboard players remove @s ${SCOREBOARD_OBJECTIVE} ${amount}`);
                selectedPlayer.runCommandAsync(`scoreboard players add @s ${SCOREBOARD_OBJECTIVE} ${amount}`);
                player.sendMessage(`§aSent §l${selectedPlayer.name} §r§2$${amount}`);
                selectedPlayer.sendMessage(`§l${player.name} §r§aHas Given You §2$${amount}`);
            } catch (e) {
                console.error("Error in money transfer:", e);
                player.sendMessage("§cAn Error Occurred");
            }
        })
        .catch((e) => {
            console.error("Form error:", e);
        });
};