use std::f32::consts::PI;
#[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, Group, MultibodyJoint, QueryFilter, RapierConfiguration,
    RapierContext, ReadMassProperties, Velocity,
};

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

const PITCH_SCALE: f32 = 0.2;

/// 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.95 {
        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 scaled_pitch_error = pitch_error * PITCH_SCALE;
    let (derivative, integral) =
        control_vars.update_pitch(scaled_pitch_error, time.delta_seconds());
    let mag =
        (settings.kp * scaled_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() > 1000 {
            dbg!(&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 braking_query: Query<&mut MultibodyJoint, (Without<CyberSteering>, With<CyberWheel>)>,
    mut body_query: Query<
        (&Transform, &mut ExternalForce),
        (With<CyberBikeBody>, Without<CyberSteering>),
    >,
    mut steering_query: Query<&mut MultibodyJoint, With<CyberSteering>>,
) {
    let (xform, mut forces) = body_query.single_mut();

    // thrust
    let thrust = xform.forward() * input.throttle * settings.accel;
    let point = xform.translation + xform.back() * 0.5;
    let force = ExternalForce::at_point(thrust, point, xform.translation);
    *forces += force;

    // brake
    for mut motor in braking_query.iter_mut() {
        let factor = if input.brake { 200.00 } else { 0.0 };
        motor.data = (*motor
            .data
            .as_revolute_mut()
            .unwrap()
            .set_motor_max_force(factor)
            .set_motor_velocity(0.0, factor))
        .into();
    }

    // steering
    let angle = input.yaw.powf(3.0) * (PI / 4.0);
    let mut steering = steering_query.single_mut();
    steering.data = (*steering
        .data
        .as_revolute_mut()
        .unwrap()
        .set_motor_position(-angle, 100.0, 0.5))
    .into();
}

/// 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: 10,
                dir: -hit.1.normal,
            });
        }
    }
}

pub(super) fn tunnel_out(
    mut commands: Commands,
    mut wheel_query: Query<
        (
            Entity,
            &mut Tunneling,
            &mut ExternalForce,
            &mut CollisionGroups,
        ),
        With<CyberWheel>,
    >,
    mprops: Query<&ReadMassProperties, With<CyberBikeBody>>,
    settings: Res<MovementSettings>,
) {
    let mprops = mprops.single();
    for (entity, mut tunneling, mut force, mut cgroups) in wheel_query.iter_mut() {
        if tunneling.frames == 0 {
            commands.entity(entity).remove::<Tunneling>();
            force.force = Vec3::ZERO;
            (cgroups.memberships, cgroups.filters) = BIKE_WHEEL_COLLISION_GROUP;
            continue;
        }
        tunneling.frames -= 1;
        force.force = tunneling.dir * settings.gravity * 1.5 * mprops.0.mass;
        //#[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);
    }
}
