use crate::{
    GameState,
    abilities::{BuildExplosionSprite, TriggerCurver},
    heads_database::HeadsDatabase,
    hitpoints::Hit,
    physics_layers::GameLayer,
    protocol::GltfSceneRoot,
    tb_entities::EnemySpawn,
    utils::{auto_rotate::AutoRotation, commands::CommandExt, global_observer},
};
use avian3d::prelude::*;
use bevy::prelude::*;
#[cfg(feature = "server")]
use lightyear::prelude::{NetworkTarget, Replicate};
use std::f32::consts::PI;

const MAX_SHOT_AGES: f32 = 15.;

#[derive(Component)]
struct CurverProjectile {
    time: f32,
    damage: u32,
}

pub fn plugin(app: &mut App) {
    app.add_systems(
        Update,
        (shot_collision, enemy_hit).run_if(in_state(GameState::Playing)),
    );
    app.add_systems(
        FixedUpdate,
        (update, timeout).run_if(in_state(GameState::Playing)),
    );

    global_observer!(app, on_trigger_missile);
}

fn on_trigger_missile(
    trigger: Trigger<TriggerCurver>,
    mut commands: Commands,
    query_transform: Query<&Transform>,
    time: Res<Time>,
    heads_db: Res<HeadsDatabase>,
) {
    let state = trigger.event().0;

    let rotation = if let Some(target) = state.target {
        let t = query_transform
            .get(target)
            .expect("target must have transform");
        Transform::from_translation(state.pos)
            .looking_at(t.translation, Vec3::Y)
            .rotation
    } else {
        state.rot.mul_quat(Quat::from_rotation_y(PI))
    };

    let head = heads_db.head_stats(state.head);

    let mut transform = Transform::from_translation(state.pos).with_rotation(rotation);
    transform.translation += transform.forward().as_vec3() * 2.0;

    let mut _projectile = commands.spawn((
        Name::new("projectile-missile"),
        CurverProjectile {
            time: time.elapsed_secs(),
            damage: head.damage,
        },
        Collider::capsule_endpoints(0.4, Vec3::new(0., 0., 2.), Vec3::new(0., 0., -2.)),
        CollisionLayers::new(
            LayerMask(GameLayer::Projectile.to_bits()),
            LayerMask(state.target_layer.to_bits() | GameLayer::Level.to_bits()),
        ),
        Sensor,
        CollisionEventsEnabled,
        Visibility::default(),
        transform,
        children![(
            Transform::from_rotation(Quat::from_rotation_x(PI / 2.).inverse()),
            AutoRotation(Quat::from_rotation_x(0.4) * Quat::from_rotation_z(0.3)),
            GltfSceneRoot::Projectile(head.projectile.clone()),
        ),],
    ));

    #[cfg(feature = "server")]
    _projectile.insert(Replicate::to_clients(NetworkTarget::All));
}

fn enemy_hit(
    mut commands: Commands,
    mut collision_event_reader: EventReader<CollisionStarted>,
    query_shot: Query<&CurverProjectile>,
    query_npc: Query<&EnemySpawn>,
) {
    for CollisionStarted(e1, e2) in collision_event_reader.read() {
        if !query_shot.contains(*e1) && !query_shot.contains(*e2) {
            continue;
        }
        if !query_npc.contains(*e1) && !query_npc.contains(*e2) {
            continue;
        }

        let (enemy_entity, projectile) = if query_npc.contains(*e1) {
            (*e1, query_shot.get(*e2))
        } else {
            (*e2, query_shot.get(*e1))
        };

        if let Ok(projectile) = projectile {
            let damage = projectile.damage;
            commands.entity(enemy_entity).trigger(Hit { damage });
        }
    }
}

fn update(mut query: Query<&mut Transform, With<CurverProjectile>>) {
    for mut transform in query.iter_mut() {
        let forward = transform.forward();
        transform.translation += forward * 0.5;
    }
}

fn timeout(mut commands: Commands, query: Query<(Entity, &CurverProjectile)>, time: Res<Time>) {
    let current_time = time.elapsed_secs();

    for (e, CurverProjectile { time, .. }) in query.iter() {
        if current_time > time + MAX_SHOT_AGES {
            commands.entity(e).despawn();
        }
    }
}

fn shot_collision(
    mut commands: Commands,
    mut collision_event_reader: EventReader<CollisionStarted>,
    query_shot: Query<&Transform, With<CurverProjectile>>,
    sensors: Query<(), With<Sensor>>,
) {
    for CollisionStarted(e1, e2) in collision_event_reader.read() {
        if !query_shot.contains(*e1) && !query_shot.contains(*e2) {
            continue;
        }

        if sensors.contains(*e1) && sensors.contains(*e2) {
            continue;
        }

        let shot_entity = if query_shot.contains(*e1) { *e1 } else { *e2 };

        let Ok(shot_pos) = query_shot.get(shot_entity).map(|t| t.translation) else {
            continue;
        };

        if let Ok(mut entity) = commands.get_entity(shot_entity) {
            entity.try_despawn();
        } else {
            continue;
        }

        commands.trigger_server(BuildExplosionSprite {
            pos: shot_pos,
            pixels_per_meter: 128.,
            time: 0.01,
        });
    }
}
