use std::{cmp::Ordering, collections::VecDeque};

use bevy::{picking::hover::HoverMap, sprite::Anchor};

use super::*;

/// Debugging systems, resources, events, etc.
pub struct DebuggingPlugin;

impl Plugin for DebuggingPlugin {
    fn build(&self, app: &mut App) {
        app.init_state::<DebuggingState>()
            .init_resource::<ToolTip>()
            .init_resource::<Fps>()
            .init_resource::<EntityCount>()
            .init_resource::<WindowInfo>()
            .init_resource::<Notice>()
            .add_systems(Startup, init_debug_ui)
            .add_systems(
                Update,
                (
                    (toggle_state_visibility::<DebuggingState>,)
                        .run_if(state_changed::<DebuggingState>),
                    toggle_debug_state.run_if(input_just_pressed(KeyCode::F12)),
                    (toggle_light_gizmo, toggle_aabb_gizmo).run_if(state_changed::<DebuggingState>),
                    (
                        (hover_mesh, hover_ui)
                            .run_if(on_message::<Pointer<Over>>.or(on_message::<Pointer<Out>>)),
                        tooltip_follow.run_if(any_component_changed::<Window>),
                        tooltip_update_transform.run_if(any_component_changed::<Transform>),
                        tooltip_draw.run_if(any_component_changed::<ToolTip>),
                        sync_resource_to_ui::<ToolTip>.run_if(resource_changed::<ToolTip>),
                        lock_tooltip.run_if(input_just_pressed(KeyCode::KeyL)),
                        track_fps,
                        sync_resource_to_ui::<Fps>.run_if(resource_changed::<Fps>),
                        track_entity_count,
                        track_window_info.run_if(any_component_changed::<Window>),
                        sync_resource_to_ui::<EntityCount>.run_if(resource_changed::<EntityCount>),
                        sync_resource_to_ui::<WindowInfo>.run_if(resource_changed::<WindowInfo>),
                        sync_resource_to_ui::<Notice>.run_if(resource_changed::<Notice>),
                    )
                        .run_if(in_state(DebuggingState::On)),
                ),
            )
            .add_observer(add_tooltip_text)
            .add_observer(populate_tooltip_info)
            .add_observer(remove_tooltip_text);

        // WebGL2-incompatible systems
        #[cfg(not(target_arch = "wasm32"))]
        {
            app.add_plugins(WireframePlugin::default())
                .insert_resource(WireframeConfig {
                    global: false,
                    default_color: MAGENTA.into(),
                })
                .add_systems(OnEnter(DebuggingState::On), enable_wireframe)
                .add_systems(OnExit(DebuggingState::On), disable_wireframe);
        }
    }
}

/// Tracks if the debugger is on or off for other games systems to hook into
///
/// The Debugging state may add it's own global debugging information, but is mostly a shell
#[derive(States, Component, Default, Debug, Clone, Hash, Eq, PartialEq)]
pub enum DebuggingState {
    #[default]
    Off,
    On,
}

/// Create the Debugging UI
fn init_debug_ui(mut commands: Commands) {
    // Version string for troubleshooting
    commands.spawn((
        DebuggingState::On,
        Name::new("Version #"),
        children![(TextColor(BLACK.into()), Text::new(VERSION),)],
        GlobalZIndex(i32::MAX - 1),
        BorderRadius::all(Val::Px(5.0)),
        BorderColor::all(BLACK),
        BackgroundColor(Color::WHITE),
        Node {
            max_width: Val::Percent(50.0),
            align_self: AlignSelf::End,
            justify_self: JustifySelf::End,
            ..default()
        },
    ));

    commands
        .spawn((
            DebuggingState::On,
            Name::new("Notice"),
            children![(
                TextColor(BLACK.into()),
                Text::new(""),
                SyncResource::<Notice>::default(),
            )],
            GlobalZIndex(i32::MAX - 1),
            BorderRadius::all(Val::Px(5.0)),
            BorderColor::all(BLACK),
            BackgroundColor(Color::WHITE),
            Node {
                max_width: Val::Percent(50.0),
                align_self: AlignSelf::End,
                justify_self: JustifySelf::Start,
                ..default()
            },
        ))
        .observe(close_on_click);

    // "Turn on Debugging" button
    commands
        .spawn((
            Node {
                align_self: AlignSelf::Start,
                justify_self: JustifySelf::End,
                flex_direction: FlexDirection::Column,
                ..default()
            },
            // When we are showing the debug button, allow this to be visible by default
            #[cfg(not(feature = "hide_debug"))]
            DebuggingState::Off,
            // Hide the "Debug Toggle" button when this feature is enabled
            #[cfg(feature = "hide_debug")]
            DebuggingState::On,
            Name::new("Debug Indicator"),
            GlobalZIndex(i32::MAX - 1),
            BorderRadius::all(Val::Px(5.0)),
            BorderColor::all(BLACK),
            BackgroundColor(Color::WHITE),
            children![(Text("Debug: OFF".into()), TextColor(BLACK.into()),)],
            Button,
        ))
        .observe(toggle_debug);

    commands
        .spawn((
            DebuggingState::On,
            Node {
                align_self: AlignSelf::Start,
                justify_self: JustifySelf::End,
                flex_direction: FlexDirection::Column,
                ..default()
            },
            BorderRadius::all(Val::Px(5.0)),
            BorderColor::all(BLACK),
            BackgroundColor(Color::WHITE),
        ))
        .with_children(|parent| {
            parent
                .spawn((
                    // Debug is active & button to toggle
                    DebuggingState::On,
                    Name::new("Debug Indicator"),
                    GlobalZIndex(i32::MAX - 1),
                    children![(Text("Debug: ON".into()), TextColor(BLACK.into()),)],
                    Button,
                ))
                .observe(toggle_debug);
            parent.spawn((
                // FPS Counter for troubleshooting
                DebuggingState::On,
                Name::new("FPS"),
                GlobalZIndex(i32::MAX - 1),
                Text::new("FPS: ##.#"),
                TextColor(BLACK.into()),
                SyncResource::<Fps>::default(),
            ));
            parent.spawn((
                // Entity count
                DebuggingState::On,
                Name::new("Entity Count"),
                GlobalZIndex(i32::MAX - 1),
                Text::new("Entities: ###"),
                TextColor(BLACK.into()),
                SyncResource::<EntityCount>::default(),
            ));
            parent.spawn((
                // Window info
                DebuggingState::On,
                Name::new("Window Info"),
                GlobalZIndex(i32::MAX - 1),
                Text::new("Window Info..."),
                TextColor(BLACK.into()),
                SyncResource::<WindowInfo>::default(),
            ));
        });

    // Tooltip
    commands
        .spawn((
            DebuggingState::On,
            SyncResource::<ToolTip>::default(),
            Pickable::IGNORE,
            GlobalZIndex(i32::MAX),
            BorderRadius::all(Val::Px(5.0)),
            BorderColor::all(BLACK),
            BackgroundColor(Color::WHITE),
            Node {
                position_type: PositionType::Absolute,
                margin: UiRect {
                    left: Val::Px(20.0),
                    ..default()
                },
                align_content: AlignContent::Center,
                justify_content: JustifyContent::Center,
                ..default()
            },
        ))
        .with_children(|parent| {
            parent.spawn((
                Text("Tooltip Placeholder".into()),
                TextColor(BLACK.into()),
                SyncResource::<ToolTip>::default(),
            ));
        });
}

/// Toggles the debug state from off -> on // off -> on when evented
fn toggle_debug_state(
    mut next: ResMut<NextState<DebuggingState>>,
    curr: Res<State<DebuggingState>>,
) {
    use DebuggingState::*;

    next.set(match curr.get() {
        On => Off,
        Off => On,
    });
    info!("Toggling debug state: {:?} -> {:?}", curr, next);
}

#[derive(Default, Resource)]
pub struct Notice(pub String);

impl Display for Notice {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(f, "{}", self.0)
    }
}

/// Add a generic Tooltip that follows the mouse in debug mode
#[derive(Default, Resource, Component)]
pub struct ToolTip(HashMap<String, String>);

impl ToolTip {
    pub fn insert(&mut self, k: &str, v: String) {
        self.0.insert(k.into(), v);
    }

    pub fn remove(&mut self, k: &str) {
        self.0.remove(k);
    }
}

impl Display for ToolTip {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for (k, v) in self.0.iter() {
            writeln!(f, "{k}: {v}")?
        }
        Ok(())
    }
}

fn tooltip_follow(
    mut tooltip: Single<(&mut Node, &mut Visibility), (With<SyncResource<ToolTip>>, Without<Text>)>,
    window: Single<&Window>,
) {
    if let Some(Vec2 { x, y }) = window.cursor_position() {
        *tooltip.1 = Visibility::Inherited;
        tooltip.0.left = Val::Px(x);
        tooltip.0.top = Val::Px(y);
    } else {
        *tooltip.1 = Visibility::Hidden;
    }
}

/// Lok tooltip to entity by inserting the Tooltip component on it
fn lock_tooltip(q: Query<Option<&ToolTip>>, hover_map: Res<HoverMap>, mut commands: Commands) {
    hover_map.0.iter().for_each(|(_, hit_data_map)| {
        if let Some((e, _)) = hit_data_map.iter().min_by(|(_, a), (_, b)| {
            if a.depth > b.depth {
                Ordering::Greater
            } else if a.depth < b.depth {
                Ordering::Less
            } else {
                Ordering::Equal
            }
        }) {
            match q.get(*e) {
                Ok(None) => {
                    info!("Adding tooltip to {:?}", e);
                    commands.entity(*e).insert(ToolTip::default());
                }
                Ok(Some(_)) => {
                    info!("Removing tooltip from {:?}", e);
                    commands.entity(*e).remove::<ToolTip>();
                }
                _ => (),
            }
        }
    });
}

/// when a tooltip is added to an entity, insert the text component
fn add_tooltip_text(event: On<Add, ToolTip>, mut commands: Commands) {
    info!("Adding text2d to {:?}", event.entity);
    commands.entity(event.entity).with_children(|parent| {
        parent.spawn((
            TextColor(BLACK.into()),
            Text2d("Placeholder".into()),
            Transform::from_xyz(0.5, 0.0, 1.0).with_scale(Vec3::splat(0.01)),
            Anchor::CENTER_LEFT,
            DebuggingState::On,
        ));
    });
}

fn populate_tooltip_info(
    event: On<Add, ToolTip>,
    mut tooltips: Query<(&mut ToolTip, Entity, &Transform, &Name)>,
) {
    if let Ok((mut tt, e, t, n)) = tooltips.get_mut(event.entity) {
        tt.insert("ID", format!("{e}"));
        tt.insert("Name", n.into());
        tt.insert(
            "Pos",
            format!(
                "{:.2?} {:.2?} {:.2?}",
                t.translation.x, t.translation.y, t.translation.z
            ),
        );
    }
}

fn tooltip_update_transform(mut events: Query<(&mut ToolTip, &Transform), Changed<Transform>>) {
    events.iter_mut().for_each(|(mut tt, t)| {
        tt.insert(
            "Pos",
            format!(
                "{:.2?} {:.2?} {:.2?}",
                t.translation.x, t.translation.y, t.translation.z
            ),
        );
    });
}

/// when a tooltip is removed to an entity, remove the text components
fn remove_tooltip_text(
    event: On<Remove, ToolTip>,
    mut commands: Commands,
    parents: Query<&Children>,
    text_2d: Query<Entity, With<Text2d>>,
) {
    // Get lis of children for this entity
    let children = parents.get(event.entity).unwrap();
    // Find the tooltip text child
    if let Some(child) = children.iter().find_map(|child| text_2d.get(child).ok()) {
        // Remove it from the world
        commands.entity(child).despawn();
    }
}

/// When tooltip is updated, re-draw it
fn tooltip_draw(
    events: Query<(&ToolTip, &Children), Changed<ToolTip>>,
    mut text_2d: Query<&mut Text2d>,
) {
    events.iter().for_each(|(tt, children)| {
        // Find the tooltip text child
        children.iter().for_each(|child| {
            if let Ok(mut text) = text_2d.get_mut(child) {
                text.0 = format!("{tt}");
            }
        });
    })
}

/// When you hover over a mesh, update the tooltip with some info
fn hover_mesh(
    mut over_events: MessageReader<Pointer<Over>>,
    mut out_events: MessageReader<Pointer<Out>>,
    mut tooltip: ResMut<ToolTip>,
    meshes: Query<(&Transform, Option<&Name>), Or<(With<Mesh3d>, With<Mesh2d>)>>,
) {
    out_events
        .read()
        .filter_map(|Pointer { entity, .. }| meshes.contains(*entity).then_some(*entity))
        .for_each(|_| {
            tooltip.remove("ID");
            tooltip.remove("Pos");
            tooltip.remove("Name");
        });
    over_events
        .read()
        .filter_map(|Pointer { entity, .. }| meshes.contains(*entity).then_some(*entity))
        .for_each(|e| {
            if let Ok((t, n)) = meshes.get(e) {
                let pos = (t.translation.x, t.translation.y, t.translation.z);
                let name = match n {
                    Some(x) => x,
                    None => "N/A",
                };
                tooltip.insert("ID", format!("{e}"));
                tooltip.insert("Pos", format!("{pos:.2?}"));
                tooltip.insert("Name", name.into());
            } else {
                warn!("Failed to query data");
            }
        });
}

fn hover_ui(
    mut over_events: MessageReader<Pointer<Over>>,
    mut out_events: MessageReader<Pointer<Out>>,
    mut tooltip: ResMut<ToolTip>,
    nodes: Query<Option<&Name>, With<Node>>,
) {
    out_events
        .read()
        .filter_map(|Pointer { entity, .. }| nodes.contains(*entity).then_some(*entity))
        .for_each(|_| {
            tooltip.remove("ID");
            tooltip.remove("Name");
        });
    over_events
        .read()
        .filter_map(|Pointer { entity, .. }| nodes.contains(*entity).then_some(*entity))
        .for_each(|e| {
            if let Ok(n) = nodes.get(e) {
                let name = match n {
                    Some(x) => x,
                    None => "N/A",
                };
                tooltip.insert("ID", format!("{e}"));
                tooltip.insert("Name", name.into());
            } else {
                warn!("Failed to query data");
            }
        });
}

#[cfg(not(target_arch = "wasm32"))]
fn enable_wireframe(mut wireframe_config: ResMut<WireframeConfig>) {
    wireframe_config.global = true;
}

#[cfg(not(target_arch = "wasm32"))]
fn disable_wireframe(mut wireframe_config: ResMut<WireframeConfig>) {
    wireframe_config.global = false;
}

// Toggle the light gizmo config group
fn toggle_light_gizmo(
    state: Res<State<DebuggingState>>,
    mut config_store: ResMut<GizmoConfigStore>,
) {
    let (_, light_group) = config_store.config_mut::<LightGizmoConfigGroup>();
    light_group.draw_all = *state.get() == DebuggingState::On;
}

// Toggle the aabb gizmo config group
fn toggle_aabb_gizmo(
    state: Res<State<DebuggingState>>,
    mut config_store: ResMut<GizmoConfigStore>,
) {
    let (_, aabb_group) = config_store.config_mut::<AabbGizmoConfigGroup>();
    aabb_group.draw_all = *state.get() == DebuggingState::On;
}

#[derive(Resource, Default, Debug)]
struct Fps(f32);

impl Display for Fps {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(f, "FPS: {:0.1}", self.0)
    }
}

fn track_fps(time: Res<Time>, mut fps: ResMut<Fps>, mut history: Local<VecDeque<f32>>) {
    // Get the time to render the last frame
    let d = time.delta_secs();

    // Add the latest delta to the list
    history.push_back(d);

    // Ensure the vecdeque doesn't get too long
    if history.len() > 64 {
        history.pop_front();
    }

    // Set FPS to 1/averageDeltaTime
    fps.0 = 1.0 / (history.iter().fold(0.0, |acc, e| acc + e) / history.len() as f32);
}

#[derive(Resource, Default, Debug)]
struct EntityCount(usize);

impl Display for EntityCount {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(f, "Entities: {}", self.0)
    }
}

fn track_entity_count(query: Query<Entity>, mut count: ResMut<EntityCount>) {
    count.0 = query.iter().len();
}

#[derive(Resource, Default, Debug)]
struct WindowInfo {
    logical_size: (f32, f32),
    physical_size: (f32, f32),
    scale_factor: f32,
    mode: String,
}

impl Display for WindowInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(
            f,
            "Res (Logi): {:?}\nRes (Phys): {:?}\nWindow Scale: {}\nWindow Mode: {}",
            self.logical_size, self.physical_size, self.scale_factor, self.mode
        )
    }
}

fn track_window_info(window: Single<&Window>, mut info: ResMut<WindowInfo>) {
    (info.logical_size.0, info.logical_size.1) =
        (window.resolution.size().x, window.resolution.size().y);
    (info.physical_size.0, info.physical_size.1) =
        (window.resolution.size().x, window.resolution.size().y);
    info.scale_factor = window.resolution.scale_factor();
    info.mode = format!("{:?}", window.mode);
}

/// Toggle the debug state when a button is clicked
fn toggle_debug(
    _event: On<Pointer<Click>>,
    curr: Res<State<DebuggingState>>,
    mut next: ResMut<NextState<DebuggingState>>,
) {
    next.set(match curr.get() {
        DebuggingState::On => DebuggingState::Off,
        DebuggingState::Off => DebuggingState::On,
    });
}

fn close_on_click(event: On<Pointer<Click>>, mut query: Query<&mut Visibility>) {
    if let Ok(mut v) = query.get_mut(event.entity) {
        *v = Visibility::Hidden;
    }
}

pub fn debug_state_changes<S: States + std::fmt::Debug>(s: Res<State<S>>) {
    info!("State changed: {:?}", s);
}
