import { world } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { VEHICLES } from "../VehiclesRoot.js";
import { handleArtilleryFire } from "./ArtilleryFireSystem.js";
import { showArtilleryControlUI } from "../TankControlUI.js";

export function showArtilleryMainGunUI(player) {
    const tankTag = Array.from(player.getTags()).find(tag => tag.startsWith('tank_'));
    if (!tankTag) return;

    const tankId = tankTag.split('_')[1];
    const tank = player.dimension.getEntities().find(e => e.id === tankId);
    if (!tank) return;

    
    const firingMode = tank.hasTag("direct_fire") ? "直接射击" :
                      tank.hasTag("indirect_fire") ? "间接射击" : "未设置";
   
    
    let targetCoords = "";
    if (tank.hasTag("indirect_fire")) {
        const x = tank.getDynamicProperty("target_x") || 0;
        const y = tank.getDynamicProperty("target_y") || 0;
        const z = tank.getDynamicProperty("target_z") || 0;
        targetCoords = `\n\n§6§l目标:§r \n§a${Math.floor(x)}, ${Math.floor(y)}, ${Math.floor(z)}`;
    }

    
    let firingRate = "未设置";
    if (tank.hasTag("firing_rate_1_second")) firingRate = "1秒";
    if (tank.hasTag("firing_rate_2_second")) firingRate = "2秒";
    if (tank.hasTag("firing_rate_3_second")) firingRate = "3秒";

    
    let fireMode = "单发";
    if (tank.hasTag("multi_2")) fireMode = "双发";
    if (tank.hasTag("multi_3")) fireMode = "三发";
    if (tank.hasTag("multi_4")) fireMode = "四发";
    if (tank.hasTag("multi_5")) fireMode = "五发";

        
        let shellType = "普通子弹";
        if (tank.getProperty("ttav:normal_shell")) shellType = "普通子弹";
        if (tank.getProperty("ttav:thermobaric_shell")) shellType = "温压弹";
        if (tank.getProperty("ttav:cluster_shell")) shellType = "集束炮弹";
    
        const statusText = 
            `§6§l射击模式:§r \n§e${firingMode}${targetCoords}\n\n` +
            `§6§l射速:§r \n§e${firingRate}\n\n` +
            `§6§l开火模式:§r \n§e${fireMode}\n\n` +
            `§6§l固定: §r\n${tank.hasTag("stationary_mode") ? "§aON" : "§cOFF"}\n\n` +
            `§6§l子弹类型:§r \n§e${shellType}\n`;
    

    const form = new ActionFormData()
        .title("主炮控制")
        .body(statusText)
        .button("保存目标", "textures/ui/ttav_buttons/normal_button")
        .button("间接射击", "textures/ui/ttav_buttons/normal_button")
        .button("子弹类型", "textures/ui/ttav_buttons/normal_button")
        .button("射速", "textures/ui/ttav_buttons/normal_button")
        .button("返回", "textures/ui/ttav_buttons/back_button")
        .button("开火", "textures/ui/ttav_buttons/powered_red_button")
        .button(
            tank.hasTag("multi_2") ? 
            "双发\n§a激活" : 
            "双发",
            tank.hasTag("multi_2") ? 
            "textures/ui/ttav_buttons/toggle_on_button" :
            "textures/ui/ttav_buttons/toggle_off_button"
        )
        .button(
            tank.hasTag("multi_3") ? 
            "三发\n§a激活" : 
            "三发",
            tank.hasTag("multi_3") ? 
            "textures/ui/ttav_buttons/toggle_on_button" :
            "textures/ui/ttav_buttons/toggle_off_button"
        )
        .button(
            tank.hasTag("multi_4") ? 
            "四发\n§a激活" : 
            "四发",
            tank.hasTag("multi_4") ? 
            "textures/ui/ttav_buttons/toggle_on_button" :
            "textures/ui/ttav_buttons/toggle_off_button"
        )
        .button(
            tank.hasTag("multi_5") ? 
            "五发\n§a激活" : 
            "五发",
            tank.hasTag("multi_5") ? 
            "textures/ui/ttav_buttons/toggle_on_button" :
            "textures/ui/ttav_buttons/toggle_off_button"
        );

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

        switch (response.selection) {
            case 0: 
            showSavedTargetsMenu(player, tank);
            player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
            break;

            case 1: 
                const vehicleConfigIndirect = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
                player.runCommand(`clear @s ${vehicleConfigIndirect.mainGunItem}`);
                showIndirectFireUI(player, tank);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                break;

            case 2: 
                showShellTypeUI(player, tank);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                break;

            case 3: 
                showFiringRateUI(player, tank);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                break;

            case 4: 
                showArtilleryControlUI(player, tank);
                player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
                return;

            case 5: 
                handleArtilleryFire(player, tank);
                player.playSound("ttavButton3", { pitch: 1.0, volume: 1.0 });
                return;

            case 6: 
                if (tank.hasTag("multi_2")) {
                    tank.removeTag("multi_2");
                } else {
                    tank.removeTag("multi_3");
                    tank.removeTag("multi_4");
                    tank.removeTag("multi_5");
                    tank.addTag("multi_2");
                }
                showArtilleryMainGunUI(player);
                player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                break;

            case 7: 
                if (tank.hasTag("multi_3")) {
                    tank.removeTag("multi_3");
                } else {
                    tank.removeTag("multi_2");
                    tank.removeTag("multi_4");
                    tank.removeTag("multi_5");
                    tank.addTag("multi_3");
                }
                showArtilleryMainGunUI(player);
                player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                break;

            case 8: 
                if (tank.hasTag("multi_4")) {
                    tank.removeTag("multi_4");
                } else {
                    tank.removeTag("multi_2");
                    tank.removeTag("multi_3");
                    tank.removeTag("multi_5");
                    tank.addTag("multi_4");
                }
                showArtilleryMainGunUI(player);
                player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                break;

            case 9: 
                if (tank.hasTag("multi_5")) {
                    tank.removeTag("multi_5");
                } else {
                    tank.removeTag("multi_2");
                    tank.removeTag("multi_3");
                    tank.removeTag("multi_4");
                    tank.addTag("multi_5");
                }
                showArtilleryMainGunUI(player);
                player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                break;
        }
    });
}
function showIndirectFireUI(player, tank) {
    const form = new ModalFormData()
        .title("设定目标坐标")
        .textField("X轴坐标", "输入X轴坐标")
        .textField("Y轴坐标", "输入Y轴坐标")
        .textField("Z轴坐标", "输入Z轴坐标");

    form.show(player).then(response => {
        if (!response || response.canceled) {
            showArtilleryMainGunUI(player);
            player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
            return;
        }

        const [x, y, z] = response.formValues;
        if (!x || !y || !z) {
            showArtilleryMainGunUI(player);
            return;
        }

        
        const targetX = parseInt(x);
        const targetY = parseInt(y);
        const targetZ = parseInt(z);

        tank.setDynamicProperty("target_x", targetX);
        tank.setDynamicProperty("target_y", targetY);
        tank.setDynamicProperty("target_z", targetZ);

        
        const deltaX = targetX - tank.location.x;
        const deltaZ = targetZ - tank.location.z;
        const angleRadians = Math.atan2(deltaZ, deltaX);
        const angleDegrees = (angleRadians * 180 / Math.PI) - 90;

        
        tank.setRotation({ x: 0, y: angleDegrees });

        
        tank.removeTag("direct_fire");
        tank.addTag("indirect_fire");
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
        showArtilleryMainGunUI(player);
    });
}


function showShellTypeUI(player, tank) {
    const form = new ActionFormData()
        .title("火炮子弹类型")
        .button("普通子弹", "textures/ui/ttav_buttons/toggle_off_button")
        .button("温压弹", "textures/ui/ttav_buttons/toggle_off_button")
        .button("集束炮弹", "textures/ui/ttav_buttons/toggle_off_button")
        .button("返回", "textures/ui/ttav_buttons/back_button");

    form.show(player).then(response => {
        if (response.canceled || response.selection === 3) {
            showArtilleryMainGunUI(player);
            player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
            return;
        }

        switch (response.selection) {
            case 0:
                tank.triggerEvent("activate_normal_shell");
                showArtilleryMainGunUI(player);
                break;
            case 1:
                tank.triggerEvent("activate_thermobaric_shell");
                showArtilleryMainGunUI(player);
                break;
            case 2:
                tank.triggerEvent("activate_cluster_shell");
                showArtilleryMainGunUI(player);
                break;
        }
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
    });
}

function showFiringRateUI(player, tank) {
    const form = new ActionFormData()
        .title("火炮射速")
        .button("1秒", "textures/ui/ttav_buttons/toggle_off_button")
        .button("2秒", "textures/ui/ttav_buttons/toggle_off_button")
        .button("3秒", "textures/ui/ttav_buttons/toggle_off_button")
        .button("返回", "textures/ui/ttav_buttons/back_button");

    form.show(player).then(response => {
        if (response.canceled || response.selection === 3) {
            showArtilleryMainGunUI(player);
            player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
            return;
        }

        
        tank.removeTag("firing_rate_1_second");
        tank.removeTag("firing_rate_2_second");
        tank.removeTag("firing_rate_3_second");

        
        switch (response.selection) {
            case 0:
                tank.addTag("firing_rate_1_second");
                break;
            case 1:
                tank.addTag("firing_rate_2_second");
                break;
            case 2:
                tank.addTag("firing_rate_3_second");
                break;
        }
        player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
        showArtilleryMainGunUI(player);
    });
}


function getSavedTargets(player) {
    return player.getTags()
        .filter(tag => tag.startsWith('ttavtrgt_'))
        .map(tag => {
            const [_, x, y, z] = tag.split('_');
            return { x: parseInt(x), y: parseInt(y), z: parseInt(z) };
        });
}
function showSavedTargetsMenu(player, tank) {
    const savedTargets = getSavedTargets(player);
    const form = new ActionFormData()
        .title("军事载具保存目标位置");

    
    for (let i = 0; i < 3; i++) {
        if (savedTargets[i]) {
            form.button(`§6目标 ${i + 1}\n§e${savedTargets[i].x}, ${savedTargets[i].y}, ${savedTargets[i].z}`);
        } else {
            form.button("§7?????\n§7??, ??, ??");
        }
    }
    
    
    form.button("§f返回", "textures/ui/ttav_buttons/back_button");

    form.show(player).then(response => {
        if (response.canceled || response.selection === 3) {
            showArtilleryMainGunUI(player);
            return;
        }

        
        if (savedTargets[response.selection]) {
            const selectedTarget = savedTargets[response.selection];
            
            tank.setDynamicProperty("target_x", selectedTarget.x);
            tank.setDynamicProperty("target_y", selectedTarget.y);
            tank.setDynamicProperty("target_z", selectedTarget.z);

            const deltaX = selectedTarget.x - tank.location.x;
            const deltaZ = selectedTarget.z - tank.location.z;
            const angleRadians = Math.atan2(deltaZ, deltaX);
            const angleDegrees = (angleRadians * 180 / Math.PI) - 90;

            tank.setRotation({ x: 0, y: angleDegrees });
            tank.removeTag("direct_fire");
            tank.addTag("indirect_fire");
            player.playSound("ttavInteract", { pitch: 1.0, volume: 1.0 });
        }
        
        showArtilleryMainGunUI(player);
    });
}

