use crate::components::*;
use bevy::prelude::*;

pub fn handle_click(
    mouse_button: Res<ButtonInput<MouseButton>>,
    windows: Query<&Window>,
    camera_query: Query<(&Camera, &GlobalTransform)>,
    mut target_query: Query<&mut MoveTarget, With<Player>>,
) {
    // Guard clause
    if !mouse_button.just_pressed(MouseButton::Right) {
        return;
    }

    let Ok(window) = windows.single() else {
        return;
    };

    let Some(cursor_position) = window.cursor_position() else {
        return;
    };

    let Ok((camera, camera_transform)) = camera_query.single() else {
        return;
    };

    let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position) else {
        return;
    };

    // check for sky clicks
    if ray.direction.y > 0.0 {
        return;
    }

    // Calculate the distance that the intercept with the ground occurs
    let t = -ray.origin.y / ray.direction.y;

    // plug T into our formula
    let intersection = ray.origin + ray.direction * t;

    for mut target in target_query.iter_mut() {
        target.position = intersection;
    }
}

pub fn move_to_target(mut query: Query<(&mut Transform, &MoveTarget, &Unit)>, time: Res<Time>) {
    for (mut transform, target, unit) in query.iter_mut() {
        let adjusted_target = target.position + Vec3::Y * unit.height_offset;
        let direction = adjusted_target - transform.translation;
        let distance = direction.length();

        // stop divide by 0 errors
        if distance < 0.001 {
            continue;
        }

        let move_amount = unit.move_speed * time.delta_secs();

        // Snap
        if distance < move_amount {
            transform.translation = adjusted_target;
        } else {
            transform.translation += direction.normalize() * move_amount;
            transform.look_at(adjusted_target, Vec3::Y);
        }
    }
}

pub fn update_progress_bar(
    player: Query<(&Player, &Transform), Without<ProgressBar>>,
    mut progress_bar: Query<(&mut Transform, &mut Visibility, &ProgressBar)>,
    camera: Query<&Transform, (With<Camera3d>, Without<ProgressBar>, Without<Player>)>,
) {
    let Ok((player, player_transform)) = player.single() else {
        return;
    };
    let Ok((mut bar_transform, mut visibility, bar_data)) = progress_bar.single_mut() else {
        return;
    };
    let Ok(camera_transform) = camera.single() else {
        return;
    };

    let progress_percent = (player.progress / 100.0).clamp(0.0, 1.0);

    // Update above player
    bar_transform.translation = player_transform.translation + Vec3::Y * bar_data.player_height;

    // Billboard effect
    let to_camera = (camera_transform.translation - bar_transform.translation).normalize();
    let angle = to_camera.z.atan2(to_camera.x);
    bar_transform.rotation = Quat::from_rotation_y(angle + std::f32::consts::FRAC_PI_2);

    bar_transform.scale.x = bar_data.width * progress_percent;

    if progress_percent == 0.0 || progress_percent == 1.0 {
        *visibility = Visibility::Hidden;
    } else {
        *visibility = Visibility::Visible;
    }
}

pub fn update_player_indicator(
    player: Query<&Player>,
    mut burger: Query<(&mut Visibility, &mut Transform), With<PlayerBurgerIndicator>>,
    time: Res<Time>,
) {
    let Ok(player_data) = player.single() else {
        return;
    };
    let Ok((mut burger_vis, mut burger_transform)) = burger.single_mut() else {
        return;
    };

    // Rotate burger
    burger_transform.rotate_y(time.delta_secs());

    // Show/hide based on inventory
    *burger_vis = if player_data.holding == Item::Burger {
        Visibility::Visible
    } else {
        Visibility::Hidden
    };
}
