use crate::prelude::*;

pub(crate) struct UiPlugin;

impl Plugin for UiPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, load_assets)
            .init_state::<Prompt>()
            .add_systems(Startup, init_prompts)
            .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>),
                    ),
                ),
            )
            .add_systems(OnEnter(GameState::Intro), show_click_prompt)
            .add_systems(OnExit(GameState::Title), hide_click_prompt)
            ;
    }
}

#[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;

#[derive(Debug, States, Hash, Default, PartialEq, Eq, Clone, Component)]
pub(crate) enum Prompt {
    #[default]
    None,
    ClickToContinue,
}

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::Grab
        // Default icon is Crosshair
        } else {
            CursorIcon::Crosshair
        }
    };
}

fn interactive_button(
    mut events: Query<(Entity, &mut UiImage, &Interaction), (With<Button>, Changed<Interaction>)>,
    mut writer: EventWriter<audio::AudioEvent>,
    children: Query<&Children>,
    mut texts: Query<(&mut Text, &mut Style)>,
    tweaks_file: Res<tweak::GameTweaks>,
    tweaks: Res<Assets<tweak::Tweaks>>,
) {
    let tweak = tweaks.get(tweaks_file.handle.clone()).expect("Load tweaks");
    let resting_handle = tweak.get_handle::<Image>("buttons_image_resting").unwrap();
    let depressed_handle = tweak
        .get_handle::<Image>("buttons_image_depressed")
        .unwrap();

    events
        .iter_mut()
        .for_each(|(entity, mut ui_image, interaction)| match interaction {
            Interaction::None => {
                ui_image.texture = resting_handle.clone();
                let mut ts = texts.iter_many_mut(children.iter_descendants(entity));
                while let Some((_t, mut s)) = ts.fetch_next() {
                    s.right = Val::Auto;
                    info!("TODO: Change text color");
                    info!("TODO: Change position");
                }
            }
            Interaction::Hovered => {
                ui_image.texture = depressed_handle.clone();
                writer.send(audio::AudioEvent::MenuHover);
                let mut ts = texts.iter_many_mut(children.iter_descendants(entity));
                while let Some((_t, mut s)) = ts.fetch_next() {
                    s.right = Val::Px(0.0);
                    info!("TODO: Change text color");
                    info!("TODO: Change position");
                }
            }
            Interaction::Pressed => {
                ui_image.texture = depressed_handle.clone();
                writer.send(audio::AudioEvent::MenuSelect);
                let mut ts = texts.iter_many_mut(children.iter_descendants(entity));
                while let Some((_t, mut s)) = ts.fetch_next() {
                    s.right = Val::Px(0.0);
                    info!("TODO: Change text color");
                    info!("TODO: Change position");
                }
            }
        });
}

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);
            if ui_scale.0 != new_scale {
                ui_scale.0 = new_scale;
            }
        }
    });
}

fn init_prompts(mut commands: Commands) {
    // ClickToContinue
    commands
        .spawn((
            Prompt::ClickToContinue,
            NodeBundle {
                style: Style {
                    position_type: PositionType::Absolute,
                    width: Val::Percent(100.0),
                    height: Val::Auto,
                    bottom: Val::Px(0.0),
                    align_items: AlignItems::Center,
                    justify_items: JustifyItems::Center,
                    justify_content: JustifyContent::Center,
                    ..default()
                },
                visibility: Visibility::Hidden,
                ..default()
            },
        ))
        .with_children(|parent| {
            parent.spawn(TextBundle {
                style: Style { ..default() },
                text: Text::from_section("Click to continue", TextStyle { ..default() }),
                visibility: Visibility::Inherited,
                ..default()
            });
        });
}

fn show_click_prompt(
    mut query: Query<(&mut Visibility, &Prompt)>,
) {
    query.iter_mut().for_each(|(mut vis, _)| *vis = Visibility::Inherited);
}

fn hide_click_prompt(
    mut query: Query<(&mut Visibility, &Prompt)>,
) {
    query.iter_mut().for_each(|(mut vis, _)| *vis = Visibility::Hidden);
}