use super::TriggerMissile;
use crate::{
    GameState,
    billboards::Billboard,
    heads_database::HeadsDatabase,
    hitpoints::Hit,
    loading_assets::GameAssets,
    physics_layers::GameLayer,
    sounds::PlaySound,
    utils::{global_observer, sprite_3d_animation::AnimationTimer, trail::Trail},
};
use avian3d::prelude::*;
use bevy::{pbr::NotShadowCaster, prelude::*};
use bevy_sprite3d::{Sprite3dBuilder, Sprite3dParams};
use std::f32::consts::PI;

const MAX_SHOT_AGES: f32 = 15.;

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

#[derive(Event, Debug)]
struct Explosion {
    position: Vec3,
    radius: f32,
    damage: u32,
}

#[derive(Resource)]
struct ShotAssets {
    image: Handle<Image>,
    layout: Handle<TextureAtlasLayout>,
}

pub fn plugin(app: &mut App) {
    app.add_systems(OnEnter(GameState::Playing), setup);
    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);
    global_observer!(app, on_explosion);
}

fn on_explosion(
    explosion: Trigger<Explosion>,
    mut commands: Commands,
    spatial_query: SpatialQuery,
) {
    let explosion = explosion.event();
    let intersections = {
        spatial_query.shape_intersections(
            &Collider::sphere(explosion.radius),
            explosion.position,
            Quat::default(),
            &SpatialQueryFilter::default().with_mask(LayerMask(
                GameLayer::Npc.to_bits() | GameLayer::Player.to_bits(),
            )),
        )
    };

    for entity in intersections.iter() {
        if let Ok(mut e) = commands.get_entity(*entity) {
            e.trigger(Hit {
                damage: explosion.damage,
            });
        }
    }
}

fn setup(mut commands: Commands, assets: Res<GameAssets>, mut sprite_params: Sprite3dParams) {
    let layout = TextureAtlasLayout::from_grid(UVec2::splat(256), 7, 6, None, None);
    let texture_atlas_layout = sprite_params.atlas_layouts.add(layout);

    commands.insert_resource(ShotAssets {
        image: assets.impact_atlas.clone(),
        layout: texture_atlas_layout,
    });
}

fn on_trigger_missile(
    trigger: Trigger<TriggerMissile>,
    mut commands: Commands,
    query_transform: Query<&Transform>,
    time: Res<Time>,
    heads_db: Res<HeadsDatabase>,
    assets: Res<GameAssets>,
    gltf_assets: Res<Assets<Gltf>>,
    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 t = Transform::from_translation(state.pos).with_rotation(rotation);
    t.translation += t.forward().as_vec3() * 2.0;

    let mesh = assets.projectiles["missile.glb"].clone();
    let asset = gltf_assets.get(&mesh).unwrap();

    commands.spawn((
        Name::new("projectile-missle"),
        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(),
        t,
        children![
            (
                Transform::from_rotation(Quat::from_rotation_x(PI / 2.).inverse())
                    .with_scale(Vec3::splat(0.04)),
                SceneRoot(asset.scenes[0].clone()),
            ),
            (
                Trail::new(
                    12,
                    LinearRgba::rgb(1., 0.0, 0.),
                    LinearRgba::rgb(0.9, 0.9, 0.)
                )
                .with_pos(t.translation),
                Gizmo {
                    handle: gizmo_assets.add(GizmoAsset::default()),
                    line_config: GizmoLineConfig {
                        width: 10.,
                        ..default()
                    },
                    ..default()
                },
            )
        ],
    ));
}

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

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)>,
    assets: Res<ShotAssets>,
    mut sprite_params: Sprite3dParams,
) {
    for CollisionStarted(e1, e2) in collision_event_reader.read() {
        if !query_shot.contains(*e1) && !query_shot.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.,
        });

        let texture_atlas = TextureAtlas {
            layout: assets.layout.clone(),
            index: 0,
        };

        commands
            .spawn(
                Sprite3dBuilder {
                    image: assets.image.clone(),
                    pixels_per_metre: 16.,
                    alpha_mode: AlphaMode::Blend,
                    unlit: true,
                    ..default()
                }
                .bundle_with_atlas(&mut sprite_params, texture_atlas),
            )
            .insert((
                Billboard,
                Transform::from_translation(shot_pos),
                NotShadowCaster,
                AnimationTimer::new(Timer::from_seconds(0.01, TimerMode::Repeating)),
            ));
    }
}
