import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { VEHICLES } from "./VehiclesRoot.js";
import { showAPVRocketControlUI, showIFVRocketControlUI } from "./TankControlUIExtension.js";
import { createTargetLaserTickingArea, removeTargetLaserTickingArea } from "./TTAVMissiles/TTAVTargetLaserChunkLoader.js";
import { reduceMainAmmo, reduceFlareAmmo, getMainAmmo, getFlareAmmo } from "./AmmoSystem.js";


const targetLasers = new Map();
const excludedTypes = ["ttav:target_laser", "minecraft:item", "ttav:homing_missile", "minecraft:xp_orb"];

function formatEntityName(entity) {
    try {
        if (!entity?.typeId) return '???';
        const rawName = entity.typeId.split(':').pop();
        return rawName
            .split('_')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join(' ');
    } catch {
        return '???';
    }
}

function getEntityDistance(entity, tank) {
    return Math.sqrt(
        Math.pow(entity.location.x - tank.location.x, 2) +
        Math.pow(entity.location.y - tank.location.y, 2) +
        Math.pow(entity.location.z - tank.location.z, 2)
    ).toFixed(1);
}

function clearTargetLaser(tank) {
    const previousLaser = targetLasers.get(tank.id);
    if (previousLaser) {
        try {
            removeTargetLaserTickingArea(previousLaser, tank.dimension);
            previousLaser.remove();
            targetLasers.delete(tank.id);
        } catch (error) {}
    }
}

function spawnTargetLaser(tank, targetEntity) {
    clearTargetLaser(tank);
    const newLaser = tank.dimension.spawnEntity("ttav:target_laser", targetEntity.location);
    targetLasers.set(tank.id, newLaser);
    createTargetLaserTickingArea(newLaser, tank.dimension);
}

export function showAPVRocketMainGunUI(player, selectedEntity = null) {
    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 nearbyEntities = tank.dimension.getEntities({
        location: tank.location,
        maxDistance: 60
    }).filter(entity => 
        entity.id !== tank.id && 
        !excludedTypes.includes(entity.typeId)
    ).slice(0, 15);

    
    nearbyEntities.sort((a, b) => {
        const distA = getEntityDistance(a, tank);
        const distB = getEntityDistance(b, tank);
        return distA - distB;
    });

    
    let bodyText = "§6扫描实体:§r §e" + nearbyEntities.length;
    if (selectedEntity) {
        const distance = getEntityDistance(selectedEntity, tank);
        bodyText += `\n§6选择目标:§r §e${formatEntityName(selectedEntity)}\n§6距离: §e${distance}§6m     §6位置: §e${Math.floor(selectedEntity.location.x)}, ${Math.floor(selectedEntity.location.y)}, ${Math.floor(selectedEntity.location.z)}`;
    }

    const form = new ActionFormData()
        .title("APV火箭主炮控制器")
        .body(bodyText)
        .button("手动目标", "textures/ui/ttav_buttons/main_gun_button")
        .button("重置", "textures/ui/ttav_buttons/powered_yellow_button")
        .button("清除目标", "textures/ui/ttav_buttons/normal_button")
        .button("开火", "textures/ui/ttav_buttons/powered_red_button")
        .button("返回", "textures/ui/ttav_buttons/back_button");

    
    for (let i = 0; i < 15; i++) {
        if (i < nearbyEntities.length) {
            const entity = nearbyEntities[i];
            const distance = getEntityDistance(entity, tank);
            const buttonText = `§f§l${formatEntityName(entity)}§r\n§6距离: §e${distance}m`;
            form.button(buttonText, "textures/ui/target_glyph");
        } else {
            form.button("§7???\n§7???", "textures/ui/lock_color");
        }
    }

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

        switch (response.selection) {
            case 0: 
                const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
                if (vehicleConfig) {
                    player.playSound("ttavButton2", { pitch: 1.0, volume: 1.0 });
                    player.runCommand(`replaceitem entity @s slot.hotbar 1 ${vehicleConfig.mainGunItem} 1 0 {"item_lock":{"mode":"lock_in_slot"},"keep_on_death":{}}`);
                }
                return;

            case 1: 
                showAPVRocketMainGunUI(player);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                return;

            case 2: 
                clearTargetLaser(tank);
                showAPVRocketMainGunUI(player);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                return;

            case 3: 
                const currentMainAmmo = getMainAmmo(tank);
                if (currentMainAmmo <= 0) {
                    player.onScreenDisplay.setActionBar("§c无弹药!");
                    player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
                    return;
                }
            
                const currentLaser = targetLasers.get(tank.id);
                if (!currentLaser) {
                    player.onScreenDisplay.setActionBar("§c未选择目标!");
                    player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
                    return;
                }
            
                if (reduceMainAmmo(tank)) {
                    const spawnLocation = {
                        x: tank.location.x,
                        y: tank.location.y + 4,
                        z: tank.location.z
                    };
                    player.playSound("ttavButton3", { pitch: 1.0, volume: 1.0 });
                    player.runCommand(`camerashake add @p[r=4] 0.1 0.1 rotational`);
                    tank.dimension.spawnEntity("ttav:homing_missile", spawnLocation);
                }
                return;
            case 4: 
                showAPVRocketControlUI(player);
                player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
                return;

                default: 
                const entityIndex = response.selection - 5;
                if (entityIndex >= 0 && entityIndex < nearbyEntities.length) {
                    const selectedEntity = nearbyEntities[entityIndex];
                    spawnTargetLaser(tank, selectedEntity);
            
                    
                    const deltaX = selectedEntity.location.x - tank.location.x;
                    const deltaZ = selectedEntity.location.z - tank.location.z;
                    const angleRadians = Math.atan2(deltaZ, deltaX);
                    const angleDegrees = (angleRadians * 180 / Math.PI) - 90;
            
                    
                    tank.setRotation({ x: 0, y: angleDegrees });
                    player.setRotation({ x: 0, y: angleDegrees });
                    player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                    showAPVRocketMainGunUI(player, selectedEntity);
                }
                return;
            
        }
    });
}
export function showIFVRocketMainGunUI(player, selectedEntity = null) {
    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 nearbyEntities = tank.dimension.getEntities({
        location: tank.location,
        maxDistance: 60
    }).filter(entity => 
        entity.id !== tank.id && 
        !excludedTypes.includes(entity.typeId)
    ).slice(0, 15);

    
    nearbyEntities.sort((a, b) => {
        const distA = getEntityDistance(a, tank);
        const distB = getEntityDistance(b, tank);
        return distA - distB;
    });

    
    let bodyText = "§6扫描实体:§r §e" + nearbyEntities.length;
    if (selectedEntity) {
        const distance = getEntityDistance(selectedEntity, tank);
        bodyText += `\n§6选择目标:§r §e${formatEntityName(selectedEntity)}\n§6距离: §e${distance}§6m     §6位置: §e${Math.floor(selectedEntity.location.x)}, ${Math.floor(selectedEntity.location.y)}, ${Math.floor(selectedEntity.location.z)}`;
    }

    const form = new ActionFormData()
        .title("APV火箭主炮控制器")
        .body(bodyText)
        .button("手动目标", "textures/ui/ttav_buttons/main_gun_button")
        .button("重置", "textures/ui/ttav_buttons/powered_yellow_button")
        .button("清除目标", "textures/ui/ttav_buttons/normal_button")
        .button("开火", "textures/ui/ttav_buttons/powered_red_button")
        .button("返回", "textures/ui/ttav_buttons/back_button");

    
    for (let i = 0; i < 15; i++) {
        if (i < nearbyEntities.length) {
            const entity = nearbyEntities[i];
            const distance = getEntityDistance(entity, tank);
            const buttonText = `§f§l${formatEntityName(entity)}§r\n§6距离: §e${distance}m`;
            form.button(buttonText, "textures/ui/target_glyph");
        } else {
            form.button("§7???\n§7???", "textures/ui/lock_color");
        }
    }

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

        switch (response.selection) {
            case 0: 
                const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
                if (vehicleConfig) {
                    player.playSound("ttavButton2", { pitch: 1.0, volume: 1.0 });
                    player.runCommand(`replaceitem entity @s slot.hotbar 1 ${vehicleConfig.mainGunItem} 1 0 {"item_lock":{"mode":"lock_in_slot"},"keep_on_death":{}}`);
                }
                return;

            case 1: 
                showIFVRocketMainGunUI(player);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                return;

            case 2: 
                clearTargetLaser(tank);
                showIFVRocketMainGunUI(player);
                player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
                return;

            case 3: 
                const currentFlareAmmo = getFlareAmmo(tank);
                if (currentFlareAmmo <= 0) {
                    player.onScreenDisplay.setActionBar("§c无弹药!");
                    player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
                    return;
                }
            
                const currentLaser = targetLasers.get(tank.id);
                if (!currentLaser) {
                    player.onScreenDisplay.setActionBar("§c未选择目标!");
                    player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
                    return;
                }
            
                if (reduceFlareAmmo(tank)) {
                    const spawnLocation = {
                        x: tank.location.x,
                        y: tank.location.y + 4,
                        z: tank.location.z
                    };
                    player.playSound("ttavButton3", { pitch: 1.0, volume: 1.0 });
                    player.runCommand(`camerashake add @p[r=4] 0.1 0.1 rotational`);
                    tank.dimension.spawnEntity("ttav:homing_missile", spawnLocation);
                }
                return;
            case 4: 
                showIFVRocketControlUI(player);
                return;

                default: 
                const entityIndex = response.selection - 5;
                if (entityIndex >= 0 && entityIndex < nearbyEntities.length) {
                    const selectedEntity = nearbyEntities[entityIndex];
                    spawnTargetLaser(tank, selectedEntity);
            
                    
                    const deltaX = selectedEntity.location.x - tank.location.x;
                    const deltaZ = selectedEntity.location.z - tank.location.z;
                    const angleRadians = Math.atan2(deltaZ, deltaX);
                    const angleDegrees = (angleRadians * 180 / Math.PI) - 90;
            
                    
                    tank.setRotation({ x: 0, y: angleDegrees });
                    player.setRotation({ x: 0, y: angleDegrees });
                    player.playSound("ttavButton4", { pitch: 1.0, volume: 1.0 });
                    showIFVRocketMainGunUI(player, selectedEntity);
                }
                return;
            
        }
    });
}
world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity } = event;
    if (deadEntity.typeId === "ttav:target_laser") {
        for (const [tankId, laser] of targetLasers.entries()) {
            if (laser.id === deadEntity.id) {
                targetLasers.delete(tankId);
                break;
            }
        }
    }
});

world.afterEvents.entityRemove.subscribe((event) => {
    if (!event.removedEntity) return;
    
    const removedEntity = event.removedEntity;
    if (removedEntity.typeId === "ttav:target_laser") {
        for (const [tankId, laser] of targetLasers.entries()) {
            if (laser.id === removedEntity.id) {
                targetLasers.delete(tankId);
                break;
            }
        }
    }
});
