#[cfg(feature = "inspector")]
use std::time::Instant;

use bevy::prelude::{Commands, Entity, Query, Res, ResMut, Time, Transform, Vec3, With, Without};
use bevy_rapier3d::prelude::{
    CollisionGroups, ExternalForce, Friction, Group, QueryFilter, RapierConfiguration,
    RapierContext, ReadMassProperties, Velocity,
};

#[cfg(feature = "inspector")]
use super::ActionDebugInstant;
use super::{CatControllerSettings, CatControllerState, MovementSettings, Tunneling};
use crate::{
    bike::{CyberBikeBody, CyberWheel, BIKE_WHEEL_COLLISION_GROUP},
    input::InputState,
};

/// Disable gravity in Rapier.
pub(super) fn zero_gravity(mut config: ResMut<RapierConfiguration>) {
    config.gravity = Vec3::ZERO;
}

/// The gravity vector points from the cyberbike to the center of the planet.
pub(super) fn gravity(
    mut query: Query<(&Transform, &mut ExternalForce, &ReadMassProperties), With<CyberBikeBody>>,
    settings: Res<MovementSettings>,
) {
    let (xform, mut forces, mprops) = query.single_mut();
    let grav = xform.translation.normalize() * -settings.gravity * mprops.0.mass;
    forces.force = grav;
    forces.torque = Vec3::ZERO;
}

/// PID-based controller for stabilizing attitude; keeps the cyberbike upright.
pub(super) fn falling_cat(
    mut bike_query: Query<(&Transform, &mut ExternalForce, &mut CatControllerState)>,
    time: Res<Time>,
    settings: Res<CatControllerSettings>,
    #[cfg(feature = "inspector")] mut debug_instant: ResMut<ActionDebugInstant>,
) {
    let (xform, mut forces, mut control_vars) = bike_query.single_mut();
    let wup = xform.translation.normalize();
    let bike_up = xform.up();

    let wright = xform.forward().cross(wup).normalize();

    let roll_error = wright.dot(bike_up);
    let pitch_error = wup.dot(xform.back());

    // only try to correct roll if we're not totally vertical
    if pitch_error.abs() < 0.8 {
        let (derivative, integral) = control_vars.update_roll(roll_error, time.delta_seconds());
        let mag =
            (settings.kp * roll_error) + (settings.ki * integral) + (settings.kd * derivative);
        if mag.is_finite() {
            forces.torque += xform.back() * mag;
        }
    }

    // we can do pitch correction any time, it's not coupled to roll
    let (derivative, integral) = control_vars.update_pitch(pitch_error, time.delta_seconds());
    let mag = (settings.kp * pitch_error) + (settings.ki * integral) + (settings.kd * derivative);
    if mag.is_finite() {
        forces.torque += wright * mag;
    }

    #[cfg(feature = "inspector")]
    {
        let now = Instant::now();
        if (now - debug_instant.0).as_millis() > 500 {
            dbg!(roll_error, pitch_error, &control_vars, mag);
            debug_instant.0 = now;
        }
    }
    control_vars.decay();
}

/// Apply forces to the cyberbike as a result of input.
pub(super) fn input_forces(
    settings: Res<MovementSettings>,
    input: Res<InputState>,
    mut cquery: Query<&mut Friction, With<CyberWheel>>,
    mut bquery: Query<(&Transform, &mut ExternalForce), With<CyberBikeBody>>,
) {
    let (xform, mut forces) = bquery.single_mut();

    // thrust
    let thrust = xform.forward() * input.throttle * settings.accel;
    forces.force += thrust;

    // brake
    for mut friction in cquery.iter_mut() {
        friction.coefficient = if input.brake { 2.0 } else { 0.0 };
    }

    // steering
    let force = xform.right() * input.yaw * settings.sensitivity;
    let point = xform.translation + xform.forward();
    let force = ExternalForce::at_point(force, point, xform.translation);
    *forces += force;
}

/// Don't let the wheels get stuck underneat the planet
pub(super) fn surface_fix(
    mut commands: Commands,
    mut wheel_query: Query<
        (Entity, &Transform, &mut CollisionGroups),
        (With<CyberWheel>, Without<Tunneling>),
    >,
    context: Res<RapierContext>,
) {
    // assume the body is not below the planet surface
    for (entity, xform, mut cgroups) in wheel_query.iter_mut() {
        let ray_dir = xform.translation.normalize();
        if let Some(hit) = context.cast_ray_and_get_normal(
            xform.translation,
            ray_dir,
            10.0,
            false,
            QueryFilter::only_fixed(),
        ) {
            cgroups.memberships = Group::NONE;
            cgroups.filters = Group::NONE;
            commands.entity(entity).insert(Tunneling {
                frames: 5,
                dir: -hit.1.normal,
            });
        }
    }
}

pub(super) fn tunnel_out(
    mut commands: Commands,
    mut wheel_query: Query<
        (
            Entity,
            &mut Tunneling,
            &mut CollisionGroups,
            &mut ExternalForce,
        ),
        With<CyberWheel>,
    >,
    settings: Res<MovementSettings>,
) {
    for (entity, mut tunneling, mut cgroups, mut force) in wheel_query.iter_mut() {
        if tunneling.frames == 0 {
            commands.entity(entity).remove::<Tunneling>();
            cgroups.memberships = BIKE_WHEEL_COLLISION_GROUP.0;
            cgroups.filters = BIKE_WHEEL_COLLISION_GROUP.1;
            continue;
        }
        tunneling.frames -= 1;
        force.force += tunneling.dir * settings.gravity * 1.1;
        #[cfg(feature = "inspector")]
        dbg!(&tunneling);
    }
}

/// General velocity-based drag-force calculation; does not take orientation
/// into account.
pub(super) fn drag(mut query: Query<(&Velocity, &mut ExternalForce), With<CyberBikeBody>>) {
    let (vels, mut forces) = query.single_mut();

    if let Some(vel) = vels.linvel.try_normalize() {
        let v2 = vels.linvel.length_squared();
        forces.force -= vel * (v2 * 0.02);
    }
}
