import { world, system } from "@minecraft/server";
import { stopCameraSystem } from "./CameraSystem.js";
import { VEHICLES } from "./VehiclesRoot.js";

const dimensions = [
    world.getDimension("minecraft:overworld"),
    world.getDimension("minecraft:nether"),
    world.getDimension("minecraft:the_end"),
];

function handleControllerItem(player, vehicle) {
    if (!player || !player.isValid()) return;
    const playerTag = `tank_${vehicle.id}`;
   
    if (!player.hasTag(playerTag)) {
        const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === vehicle.typeId);
        if (vehicleConfig) {
            player.runCommand(`replaceitem entity @s slot.hotbar 0 ${vehicleConfig.controllerItem} 1 0 {"item_lock":{"mode":"lock_in_slot"},"keep_on_death":{}}`);
        }
    }
}

function handleTags(player, vehicle) {
    if (!player || !player.isValid() || !vehicle || !vehicle.isValid()) return;
    const playerTag = `tank_${vehicle.id}`;
    const vehicleTag = `rider_${player.id}`;
   
    if (!player.hasTag(playerTag)) {
        player.addTag(playerTag);
        vehicle.addTag(vehicleTag);
    }
}

function handleDismount(vehicle) {
    if (!vehicle || !vehicle.isValid()) return;
    const riderTag = Array.from(vehicle.getTags()).find(tag => tag.startsWith('rider_'));
    if (riderTag) {
        const riderId = riderTag.split('_')[1];
        vehicle.removeTag(riderTag);
       
        const engineOn = vehicle.getDynamicProperty("ttav:engine");
       
        for (const dimension of dimensions) {
            const players = dimension.getPlayers();
            for (const player of players) {
                if (player && player.isValid() && player.id === riderId) {
                    if (engineOn) {
                        player.playSound("ttavTankEngineStop", { pitch: 1.0, volume: 1.0 });
                    }
                    system.runTimeout(() => {
                        if (player && player.isValid()) {
                            player.runCommand(`camera @s clear`);
                            stopCameraSystem();
                        }
                    }, 5);
                    cleanupPlayer(player);
                    player.playSound("ttavTankDoorOpen_close", { pitch: 1.0, volume: 1.0 });
                    break;
                }
            }
        }

        vehicle.triggerEvent("engine_off");
        vehicle.setDynamicProperty("ttav:engine", false);
        vehicle.removeTag("stationary_mode");
    }
}

function cleanupPlayer(player) {
    if (!player || !player.isValid()) return;
    stopCameraSystem();
   
    const playerTags = player.getTags();
    for (const tag of playerTags) {
        if (tag.startsWith('tank_')) {
            const tankId = tag.split('_')[1];
           
            for (const dimension of dimensions) {
                const tank = dimension.getEntities().find(e => e.id === tankId);
                if (tank) {
                    const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
                    if (vehicleConfig) {
                        player.runCommand(`clear @s ${vehicleConfig.mainGunItem}`);
                        player.runCommand(`clear @s ${vehicleConfig.subGunItem}`);
                        player.runCommand(`clear @s ${vehicleConfig.flareGunItem}`);
                    }
                    break;
                }
            }
            player.runCommand(`effect @s clear`);
            player.removeTag(tag);
            player.onScreenDisplay.setTitle("tank_clear_cam");
        }
    }

    for (const dimension of dimensions) {
        const vehicles = dimension.getEntities();
        for (const vehicle of vehicles) {
            const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === vehicle.typeId);
            if (vehicleConfig) {
                const vehicleTags = vehicle.getTags();
                for (const tag of vehicleTags) {
                    if (tag.startsWith('rider_')) {
                        vehicle.removeTag(tag);
                    }
                }
            }
        }
    }
   
    for (const vehicle of Object.values(VEHICLES)) {
        player.runCommand(`clear @s ${vehicle.controllerItem}`);
    }
}

function checkRidingStates() {
    for (const dimension of dimensions) {
        for (const [vehicleType, config] of Object.entries(VEHICLES)) {
            const vehicles = dimension.getEntities({ type: config.identifier });
           
            for (const vehicle of vehicles) {
                if (!vehicle || !vehicle.isValid()) continue;
                const rideableComponent = vehicle.getComponent("minecraft:rideable");
                if (!rideableComponent) {
                    continue;
                }

                const riders = rideableComponent.getRiders();
                if (riders.length > 0 && riders[0] && riders[0].isValid()) {
                    handleControllerItem(riders[0], vehicle);
                    system.runTimeout(() => {
                        handleTags(riders[0], vehicle);
                    }, 5);
                } else {
                    handleDismount(vehicle);
                }
            }
        }
    }
}

world.afterEvents.playerLeave.subscribe((event) => {
    if (event.player && event.player.isValid()) {
        cleanupPlayer(event.player);
    }
});

world.afterEvents.playerJoin.subscribe((event) => {
    if (event.player && event.player.isValid()) {
        cleanupPlayer(event.player);
    }
});

world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity } = event;
    if (!deadEntity || !deadEntity.isValid()) return;

    if (deadEntity.typeId === "minecraft:player") {
        const playerTags = deadEntity.getTags();
        for (const tag of playerTags) {
            if (tag.startsWith('tank_')) {
                deadEntity.removeTag(tag);
            }
        }
        stopCameraSystem();
        cleanupPlayer(deadEntity);
    } else {
        const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === deadEntity.typeId);
        if (vehicleConfig) {
            const riderTag = Array.from(deadEntity.getTags()).find(tag => tag.startsWith('rider_'));
            if (riderTag) {
                const riderId = riderTag.split('_')[1];
                deadEntity.removeTag(riderTag);
                for (const dimension of dimensions) {
                    const players = dimension.getPlayers();
                    for (const player of players) {
                        if (player && player.isValid() && player.id === riderId) {
                            const tankTag = Array.from(player.getTags()).find(tag => tag.startsWith('tank_'));
                            if (tankTag) {
                                stopCameraSystem();
                                player.removeTag(tankTag);
                                player.onScreenDisplay.setTitle("tank_clear_cam");
                            }
                            cleanupPlayer(player);
                            break;
                        }
                    }
                }
            }
        }
    }
});

world.afterEvents.entityRemove.subscribe((event) => {
    if (!event.removedEntity || !event.removedEntity.isValid()) return;
   
    const removedEntity = event.removedEntity;

    if (removedEntity.typeId === "minecraft:player") {
        const playerTags = removedEntity.getTags();
        for (const tag of playerTags) {
            if (tag.startsWith('tank_')) {
                removedEntity.removeTag(tag);
            }
        }
        stopCameraSystem();
        cleanupPlayer(removedEntity);
    } else {
        const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === removedEntity.typeId);
        if (vehicleConfig) {
            const riderTag = Array.from(removedEntity.getTags()).find(tag => tag.startsWith('rider_'));
            if (riderTag) {
                const riderId = riderTag.split('_')[1];
                removedEntity.removeTag(riderTag);
                for (const dimension of dimensions) {
                    const players = dimension.getPlayers();
                    for (const player of players) {
                        if (player && player.isValid() && player.id === riderId) {
                            const tankTag = Array.from(player.getTags()).find(tag => tag.startsWith('tank_'));
                            if (tankTag) {
                                stopCameraSystem();
                                player.runCommand(`camera @s clear`);
                                player.removeTag(tankTag);
                            }
                            cleanupPlayer(player);
                            break;
                        }
                    }
                }
            }
        }
    }
});

system.runInterval(checkRidingStates, 10);
