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

const TUTORIAL_ITEM = "minecraft:stick";
const TANK_PRICES = {
    ABRAMS: { price: 62,controller: "pn:abrams1_spawn_egg" },     
    ARMATA: { price: 64,controller: "pn:armata1_spawn_egg" },     
    BRADLEY: { price: 42,controller: "pn:bradley1_spawn_egg" },    
    CHIEFTAIN: { price: 42,controller: "pn:chieftain1_spawn_egg" },
    DOHER: { price: 44,controller: "pn:doher1_spawn_egg" },       
    HARIMAU: { price: 38,controller: "pn:harimau1_spawn_egg" },   
    HIMARS: { price: 58,controller: "pn:himars1_spawn_egg" },     
    K2BP: { price: 60,controller: "pn:k2bp1_spawn_egg" },         
    LECLERC: { price: 56,controller: "pn:leclerc1_spawn_egg" },   
    MERKAVA: { price: 58,controller: "pn:merkava1_spawn_egg" },   
    M270: { price: 54,controller: "pn:m2701_spawn_egg" },         
    PALADIN: { price: 50,controller: "pn:paladin1_spawn_egg" },   
    STRV122: { price: 57,controller: "pn:strv1221_spawn_egg" },   
    T90: { price: 52,controller: "pn:t901_spawn_egg" },           
    TUNGUSKA: { price: 48,controller: "pn:tunguska1_spawn_egg" }, 
    TYPE10: { price: 59,controller: "pn:type101_spawn_egg" },     
    URAGAN: { price: 46,controller: "pn:uragan1_spawn_egg" },     
    VT5: { price: 36,controller: "pn:vt51_spawn_egg" },
    T72: { price: 30,controller: "pn:t721_spawn_egg" },
    T99CN: { price: 61,controller: "pn:t99cn1_spawn_egg" }
};

function handleTankPurchase(player, page, selection) {
    let tankName;
    switch(page) {
        case 1:
            tankName = ["ABRAMS", "ARMATA", "BRADLEY", "CHIEFTAIN", "DOHER", "HARIMAU"][selection];
            break;
        case 2:
            tankName = ["HIMARS", "K2BP", "LECLERC", "MERKAVA", "M270", "PALADIN"][selection];
            break;
        case 3:
            tankName = ["STRV122", "T90", "TUNGUSKA", "TYPE10", "URAGAN", "VT5"][selection];
            break;
        case 4:
            tankName = ["T72", "T99CN", null, null, null, null][selection];
            break;
    }

    if (!tankName) return;

    const tank = TANK_PRICES[tankName];
    const inventory = player.getComponent("minecraft:inventory");
    let diamondCount = 0;

    for (let i = 0; i < inventory.container.size; i++) {
        const item = inventory.container.getItem(i);
        if (item?.typeId === "minecraft:diamond") {
            diamondCount += item.amount;
        }
    }

    if (diamondCount >= tank.price) {
        player.runCommand(`clear @s diamond 0 ${tank.price}`);
        player.runCommand(`give @s ${tank.controller}`);
        player.sendMessage(`§a已成功购买${tankName}!`);
        player.playSound("random.levelup", { pitch: 1.0, volume: 1.0 });
    } else {
        player.sendMessage(`§c钻石不够！需要${tank.price}钻石.`);
        player.playSound("note.bass", { pitch: 0.5, volume: 1.0 });
    }
}

function showTankShop(player, page = 1) {
    const form = new ActionFormData()
        .title("军事载具商店");

    switch(page) {
        case 1:
            form.button("§f艾布拉姆斯坦克", "textures/items/price/abrams")
                .button("§fT-14阿玛塔坦克", "textures/items/price/armata")
                .button("§f布拉德利步兵战车", "textures/items/price/bradley")
                .button("§f酋长MKV型坦克", "textures/items/price/chieftain")
                .button("§fM109多赫尔/罗切夫火炮", "textures/items/price/doher")
                .button("§f哈里莫坦克", "textures/items/price/harimau")
                .button("§f返回", "textures/ui/arrow_left")
                .button("§f继续", "textures/ui/arrow_right");
            break;
        case 2:
            form.button("§f海马斯多管火箭炮", "textures/items/price/himars")
                .button("§fK-2黑豹主战坦克", "textures/items/price/k2bp")
                .button("§f勒克莱尔XLR型坦克", "textures/items/price/leclerc")
                .button("§f梅卡瓦IV型坦克", "textures/items/price/merkava")
                .button("§fM270多管火箭炮", "textures/items/price/m270")
                .button("§fM109帕拉丁火炮", "textures/items/price/paladin")
                .button("§f返回", "textures/ui/arrow_left")
                .button("§f继续", "textures/ui/arrow_right");
            break;
        case 3:
            form.button("§fStrv-122型瑞典主战坦克", "textures/items/price/strv")
                .button("§fT-90型坦克", "textures/items/price/t90")
                .button("§f通古斯卡防空系统", "textures/items/price/tunguska")
                .button("§f10式主战坦克", "textures/items/price/type10")
                .button("§fBM-27飓风火箭炮", "textures/items/price/uragan")
                .button("§fVT-5型坦克", "textures/items/price/vt5")
                .button("§f返回", "textures/ui/arrow_left")
                .button("§f继续", "textures/ui/arrow_right");
            break;
        case 4:
            form.button("§fT-72型主战坦克", "textures/items/price/t72")
                .button("§fT-99型主战坦克", "textures/items/price/t99")
                .button("§f锁定", "textures/items/price/coming_soon")
                .button("§f锁定", "textures/items/price/coming_soon")
                .button("§f锁定", "textures/items/price/coming_soon")
                .button("§f锁定", "textures/items/price/coming_soon")
                .button("§f返回", "textures/ui/arrow_left")
                .button("§f继续", "textures/ui/arrow_right");
            break;
    }

    form.show(player).then(response => {
        if (response.canceled) return;
        
        const selection = response.selection;
        const isBack = selection === 6;
        const isNext = selection === 7;
        const isLocked = page === 4 && selection > 1 && selection < 6;
    
        if (isBack) {
            if (page === 1) {
                showMainShop(player);
            } else {
                showTankShop(player, page - 1);
            }
        } else if (isNext) {
            showTankShop(player, page < 4 ? page + 1 : 1);
        } else if (isLocked) {
            showTankShop(player, page);
            player.playSound("note.bass", { pitch: 0.5, volume: 1.0 });
        } else {
            handleTankPurchase(player, page, selection);
        }
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
    });
}

export function openTankShop(player) {
    showTankShop(player);
}

function showMainShop(player) {
    const form = new ActionFormData()
        .title("商店选项")
        .button("§f载具商店", "textures/items/vehicles/abrams")
        .button("§f物品商店", "textures/items/tank_equipment")
        .button("§f返回", "textures/ui/arrow_left");

    form.show(player).then(response => {
        if (response.canceled) return;
        
        switch(response.selection) {
            case 0:
                showTankShop(player);
                break;
            case 1:
                showItemShop(player);
                break;
            case 2:
                break;
        }
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
    });
}

const ITEM_PRICES = {
    GASOLINE: { price: 1, item: "ttav:gasoline" },
    EQUIPMENT: { price: 10, item: "ttav:tank_equipment" },
    TARGET_FINDER: { price: 10, item: "ttav:target_finder_controller" },
    SUB_GUN: { price: 5, item: "ttav:tank_sub_gun" },
    FLARE_GUN: { price: 5, item: "ttav:tank_flare_gun" },
    MAIN_GUN: { price: 5, item: "ttav:tank_main_gun" }
};

function handleItemPurchase(player, selection) {
    const items = Object.values(ITEM_PRICES);
    const item = items[selection];

    if (!item) return;

    const inventory = player.getComponent("minecraft:inventory");
    let diamondCount = 0;

    for (let i = 0; i < inventory.container.size; i++) {
        const invItem = inventory.container.getItem(i);
        if (invItem?.typeId === "minecraft:diamond") {
            diamondCount += invItem.amount;
        }
    }

    if (diamondCount >= item.price) {
        player.runCommand(`clear @s diamond 0 ${item.price}`);
        player.runCommand(`give @s ${item.item}`);
        player.sendMessage(`§a已成功购买商品!`);
        player.playSound("random.levelup", { pitch: 1.0, volume: 1.0 });
    } else {
        player.sendMessage(`§c钻石不够！需要${item.price}钻石.`);
        player.playSound("note.bass", { pitch: 0.5, volume: 1.0 });
    }
}

function showItemQuantityModal(player, itemType) {
    const form = new ModalFormData()
        .title("选择数量")
        .slider("合计", 1, 64, 1);

    form.show(player).then(response => {
        if (response.canceled) {
            showItemShop(player);
            return;
        }

        const quantity = response.formValues[0];
        const items = Object.values(ITEM_PRICES);
        const item = items[itemType];
        const totalPrice = item.price * quantity;

        const inventory = player.getComponent("minecraft:inventory");
        let diamondCount = 0;

        for (let i = 0; i < inventory.container.size; i++) {
            const invItem = inventory.container.getItem(i);
            if (invItem?.typeId === "minecraft:diamond") {
                diamondCount += invItem.amount;
            }
        }

        if (diamondCount >= totalPrice) {
            player.runCommand(`clear @s diamond 0 ${totalPrice}`);
            player.runCommand(`give @s ${item.item} ${quantity}`);
            player.sendMessage(`§a成功购买${quantity} 件物品!`);
            player.playSound("random.levelup", { pitch: 1.0, volume: 1.0 });
        } else {
            player.sendMessage(`§c钻石不够！需要${totalPrice}钻石.`);
            player.playSound("note.bass", { pitch: 0.5, volume: 1.0 });
        }
        showItemShop(player);
    });
}

function showItemShop(player) {
    const form = new ActionFormData()
        .title("军事载具主商店")
        .button("§f汽油\n§e价格: §f1 §b钻石", "textures/items/jirigen")
        .button("§f坦克装备\n§e价格: §f10 §b钻石", "textures/items/tank_equipment")
        .button("§f目标查找器\n§e价格: §f10 §b钻石", "textures/items/ttav_controller_finder")
        .button("§f副炮\n§e价格: §f5 §b钻石", "textures/items/ttva_sub_ammo")
        .button("§f信号枪\n§e价格: §f5 §b钻石", "textures/items/ttva_fla_ammo")
        .button("§f主炮\n§e价格: §f5 §b钻石", "textures/items/ttva_main_ammo")
        .button("§f返回", "textures/ui/arrow_left")
        .button("§f关闭", "textures/ui/close");

    form.show(player).then(response => {
        if (response.canceled) return;
        
        if (response.selection === 6) {
            showMainShop(player);
            return;
        }
        if (response.selection === 7) {
            return;
        }

        
        const itemType = response.selection;
        if ([0, 3, 4, 5].includes(itemType)) {
            showItemQuantityModal(player, itemType);
        } else {
            handleItemPurchase(player, itemType);
        }
        
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
    });
}


world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    const { player, target } = event;
    
    if (target.typeId === "pn:cavalry_commander") {
        showMainShop(player);
    }
});

world.afterEvents.entityHitEntity.subscribe((event) => {
    const { damagingEntity, hitEntity } = event;
    
    if (hitEntity?.typeId === "pn:cavalry_commander" && damagingEntity.typeId === "minecraft:player") {
        showMainShop(damagingEntity);
    }
});

function giveTutorialItem(player) {
    const hasTutorialCompleteTag = player.hasTag("ttav_tutorial_complete");

    if (!hasTutorialCompleteTag) {
        player.runCommand(`give @s pn:cavalry_commander_spawn_egg`);
        player.runCommand(`tag @s add ttav_tutorial_complete`);
    }
}

world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
    if (!initialSpawn) return;
    giveTutorialItem(player);
});
