use std::f32::consts::PI;

use bevy::{
	math::bounding::{Aabb2d, BoundingCircle, IntersectsVolume},
	prelude::*,
};

// use rand::Rng;
use crate::{
	common::{
		animation::{AnimationPlugin, SpriteAnimation},
		path_follow::{PathFollow2D, PathFollow2DPlugin},
		velocity::{Velocity, VelocityPlugin},
	},
	enemy::{Enemy, EnemyPlugin},
	hud::{HUDPlugin, StartMenuUI},
	player::{Player, PlayerPlugin},
	score::{Score, ScorePlugin},
	GameOverEvent, GameState,
};

pub struct LevelPlugin;

impl Plugin for LevelPlugin {
	fn build(&self, app: &mut App) {
		app.add_plugins(ScorePlugin);
		app.add_plugins(PlayerPlugin);
		app.add_plugins(EnemyPlugin);
		app.add_plugins(HUDPlugin);
		app.add_plugins(VelocityPlugin);
		app.add_plugins(AnimationPlugin);
		app.add_plugins(PathFollow2DPlugin);
		app.insert_resource(SpawnTimer(Timer::from_seconds(0.5, TimerMode::Repeating)));
		app.add_systems(Startup, setup);
		app.add_systems(Update, (debug_gizmos, debug_gizmos_config));
		app.add_systems(
			FixedUpdate,
			(spawn_enemy, check_for_collisions, game_over).run_if(in_state(GameState::Playing)),
		);
	}
}

fn setup(mut commands: Commands) {
	commands.spawn(PathFollow2D {
		progress: 0.0,
		points: vec![
			Vec2::new(0.0, 720.0),
			Vec2::new(480.0, 720.0),
			Vec2::new(480.0, 0.0),
			Vec2::new(0.0, 0.0),
		],
		looping: true,
	});
}

#[derive(Resource, Deref, DerefMut)]
struct SpawnTimer(Timer);

#[derive(Component, Default)]
#[require(Sprite, Velocity, Collider)]
pub struct Unit;

#[derive(Component, Default)]
pub struct Collider;

#[derive(Event, Default)]
pub struct CollisionEvent;

fn spawn_enemy(
	mut commands: Commands,
	asset_server: Res<AssetServer>,
	time: Res<Time>,
	mut timer: ResMut<SpawnTimer>,
	path: Query<&PathFollow2D>,
	mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
	timer.tick(time.delta());
	if timer.finished() {
		let path = path.single();

		let rng = fastrand::f32();

		let (spawn_pos, path_dir) = path.get_pos(rng);

		let path_dir = path_dir.to_angle() - PI / 2.0;

		let random_angle = fastrand::f32() * 2.0 - 1.0;
		let random_angle = random_angle * (PI / 4.0);

		let path_dir = path_dir + random_angle;
		let direction = Vec2::from_angle(path_dir);
		let velocity = direction.normalize() * fastrand::u32(150..350) as f32;
		let direction = Quat::from_rotation_z(direction.to_angle());

		let (idx, grid) = match fastrand::u32(0..3) {
			0 => (1, UVec2::new(135, 96)),
			1 => (2, UVec2::new(132, 96)),
			2 => (3, UVec2::new(110, 190)),
			_ => (1, UVec2::new(135, 96)),
		};
		let idx = format!("enemy{idx}.png");

		let layout = TextureAtlasLayout::from_grid(grid, 2, 1, None, None);
		let texture_atlas_layouts = texture_atlas_layouts.add(layout);

		commands.spawn((
			Enemy,
			Transform {
				translation: spawn_pos.extend(1.0),
				rotation: direction,
				scale: Vec2::new(0.75, 0.75).extend(1.0),
			},
			Sprite {
				image: asset_server.load(idx),
				texture_atlas: Some(TextureAtlas {
					layout: texture_atlas_layouts,
					index: 0,
				}),
				..Default::default()
			},
			SpriteAnimation::new(1, Timer::from_seconds(0.3, TimerMode::Repeating)),
			Velocity(velocity),
		));
	}
}

fn check_for_collisions(
	commands: Commands,
	score: ResMut<Score>,
	mut player_query: Query<(&mut Velocity, &Transform), With<Player>>,
	collider_query: Query<(Entity, &Transform), (With<Collider>, With<Enemy>)>,
	mut game_over_events: EventWriter<GameOverEvent>,
) {
	let (player_velocity, player_transform) = player_query.single_mut();

	for (collider_entity, collider_transform) in &collider_query {
		let collision = player_collision(
			BoundingCircle::new(player_transform.translation.truncate(), 20.0),
			BoundingCircle::new(collider_transform.translation.truncate(), 30.0).aabb_2d(),
		);

		// game over
		if collision {
			game_over_events.send_default();
		}
	}
}

fn game_over(
	mut commands: Commands,
	asset_server: Res<AssetServer>,
	mut state: ResMut<NextState<GameState>>,
	mut player_query: Query<&mut Visibility, With<Player>>,
	enemies_query: Query<Entity, With<Enemy>>,
	mut ui_elems_query: Query<&mut Visibility, (With<StartMenuUI>, Without<Player>)>,
	mut game_over_events: EventReader<GameOverEvent>,
) {
	if game_over_events.is_empty() {
		return;
	}

	game_over_events.clear();
	state.set(GameState::Menu);

	let mut player_visibility = player_query.single_mut();
	*player_visibility = Visibility::Hidden;

	for mut elem in &mut ui_elems_query {
		*elem = Visibility::Visible;
	}

	for enemy in &enemies_query {
		commands.entity(enemy).despawn();
	}

	commands.spawn((
		AudioPlayer::new(asset_server.load("gameover.wav")),
		PlaybackSettings::DESPAWN,
	));
}

fn player_collision(player: BoundingCircle, bounding_box: Aabb2d) -> bool {
	if !player.intersects(&bounding_box) {
		return false;
	}

	true
}

fn debug_gizmos(gizmos: Gizmos, query: Query<&PathFollow2D>) {
	for path in &query {
		// let x = path.points.len();
		// for i in 0..x {
		// 	if i < x - 1 {
		// 		gizmos.line_2d(path.points[i], path.points[i + 1], LIME);
		// 	}
		// 	else if path.looping && x > 2 {
		// 		gizmos.line_2d(path.points[i], path.points[0], LIME);
		// 	}
		// }

		// let p = path.get_pos(0.125);
		// gizmos.circle_2d(p, 15.0, RED);
	}
}

fn debug_gizmos_config(mut config_store: ResMut<GizmoConfigStore>) {
	let (config, _) = config_store.config_mut::<DefaultGizmoConfigGroup>();
	// config.line_width = 15.0;
}
