use bevy::window::PrimaryWindow;

use crate::prelude::*;

pub(crate) struct UiPlugin;

impl Plugin for UiPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, load_assets).add_systems(
            Update,
            (
                manage_cursor.run_if(
                    any_component_changed::<Interaction>.or_else(state_changed::<GameState>()),
                ),
                interactive_button.run_if(any_component_changed::<Interaction>),
                scale_ui.run_if(
                    on_event::<AssetEvent<tweak::Tweaks>>()
                        .or_else(any_component_changed::<Window>)
                        .and_then(resource_exists::<tweak::GameTweaks>()),
                ),
            ),
        );
    }
}

#[derive(Debug, Component)]
struct UiRoot;

#[derive(Debug, Resource)]
pub(crate) struct UiFont {
    pub handle: Handle<Font>,
}

#[derive(Debug, Component)]
pub(crate) struct TextScroll {
    pub progress: usize,
    pub start: f32,
}

#[derive(Debug, Component)]
pub(crate) struct TextScrollAnimation;

fn load_assets(server: ResMut<AssetServer>, mut commands: Commands) {
    commands.insert_resource(UiFont {
        handle: server.load("fonts/Silkscreen/Silkscreen-Regular.ttf"),
    });
}

fn manage_cursor(
    mut window: Query<&mut Window, With<PrimaryWindow>>,
    state: Res<State<GameState>>,
    buttons: Query<&Interaction, With<Button>>,
) {
    window.single_mut().cursor.icon = {
        // In Loading state, icon is Progess/Wait
        if *state == GameState::Loading {
            CursorIcon::Wait
        // If a button is hovered, icon is hand
        } else if buttons.iter().any(|i| *i == Interaction::Pressed) {
            CursorIcon::Grabbing
        // If a button is clicked, icon is grab
        } else if buttons.iter().any(|i| *i == Interaction::Hovered) {
            CursorIcon::Hand
        // Default icon is Crosshair
        } else {
            CursorIcon::Crosshair
        }
    };
}

fn interactive_button(
    mut events: Query<(&mut BackgroundColor, &Interaction), (With<Button>, Changed<Interaction>)>,
    mut writer: EventWriter<audio::AudioEvent>,
) {
    events
        .iter_mut()
        .for_each(|(mut bg_color, interaction)| match interaction {
            Interaction::None => {
                bg_color.0.set_a(0.5);
            }
            Interaction::Hovered => {
                bg_color.0.set_a(0.75);
                writer.send(audio::AudioEvent::MenuHover);
            }
            Interaction::Pressed => {
                bg_color.0.set_a(1.0);
                writer.send(audio::AudioEvent::MenuSelect);
            }
        });
}

fn scale_ui(
    mut windows: Query<&mut Window, Changed<Window>>,
    mut ui_scale: ResMut<UiScale>,
    mut resolution_set: Local<bool>,
    tweakfile: Res<tweak::GameTweaks>,
    tweaks: Res<Assets<tweak::Tweaks>>,
) {
    if !tweaks.contains(tweakfile.handle.clone()) {
        return;
    }
    let tweak = tweaks.get(tweakfile.handle.clone()).unwrap();
    let width = tweak.get::<f32>("resolution_x").unwrap();
    let height = tweak.get::<f32>("resolution_y").unwrap();

    windows.iter_mut().for_each(|mut w| {
        // Setting window resolution at startup
        if !*resolution_set {
            w.resolution.set(width, height);
            *resolution_set = true;
        }

        // Check if window is minimized
        if w.resolution.height() > 0.0 && w.resolution.height() > 0.0 {
            // Setting UI Scale based on ratio of expected to current ratio
            let width_ratio = w.resolution.width() / width;
            let height_ratio = w.resolution.height() / height;
            let new_scale = (width_ratio).min(height_ratio) as f64;
            if ui_scale.0 != new_scale {
                ui_scale.0 = new_scale;
            }
        }
    });
}
