use super::TriggerMissile;
use crate::{
    GameState,
    abilities::BuildExplosionSprite,
    heads_database::HeadsDatabase,
    physics_layers::GameLayer,
    protocol::{GltfSceneRoot, PlaySound},
    utils::{commands::CommandExt, explosions::Explosion, global_observer, trail::Trail},
};
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.;
const MISSLE_SPEED: f32 = 3.;

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

pub fn plugin(app: &mut App) {
    app.add_systems(Update, shot_collision.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<TriggerMissile>,
    mut commands: Commands,
    query_transform: Query<&Transform>,
    time: Res<Time>,
    heads_db: Res<HeadsDatabase>,
    mut gizmo_assets: ResMut<Assets<GizmoAsset>>,
) {
    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"),
        MissileProjectile {
            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()),
                GltfSceneRoot::Projectile("missile".to_string()),
            ),
            (
                Trail::new(
                    12,
                    LinearRgba::rgb(1., 0.0, 0.),
                    LinearRgba::rgb(0.9, 0.9, 0.)
                )
                .with_pos(transform.translation),
                Gizmo {
                    handle: gizmo_assets.add(GizmoAsset::default()),
                    line_config: GizmoLineConfig {
                        width: 10.,
                        ..default()
                    },
                    ..default()
                },
            )
        ],
    ));
    #[cfg(feature = "server")]
    _projectile.insert(Replicate::to_clients(NetworkTarget::All));
}

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

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

    for (e, MissileProjectile { 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<(&MissileProjectile, &Transform)>,
    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, damage)) = query_shot
            .get(shot_entity)
            .map(|(projectile, t)| (t.translation, projectile.damage))
        else {
            continue;
        };

        commands.trigger(PlaySound::MissileExplosion);

        commands.entity(shot_entity).despawn();

        commands.trigger(Explosion {
            damage,
            position: shot_pos,
            radius: 6.,
        });

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