use bevy::{prelude::*, state::state::FreelyMutableState};
use lib::{
    ItemPosition, MenuItemType, OnPressAction,
    menus::{Menu, Menus},
};

use crate::AppState;

mod lib;

#[derive(States, Debug, Copy, Clone, PartialEq, Eq, Hash, Default, Reflect)]
pub enum CurrentMenu {
    NotInMenus,
    #[default]
    MainMenu,
    Settings,
    HighScores,
    StartGame,
}

fn switch_state<S: States + FreelyMutableState>(target: S) -> impl Fn(ResMut<NextState<S>>) {
    move |mut next_state: ResMut<NextState<S>>| {
        next_state.set(target.clone());
    }
}

pub fn plugin(app: &mut App) {
    let start_game_state = app.register_system(switch_state(AppState::Ingame));
    let plugin = Menus::<AppState, CurrentMenu>::new(AppState::Menus, CurrentMenu::NotInMenus)
        .add_menu(
            CurrentMenu::MainMenu,
            Menu::new().add_items(&[
                &MenuItemType::Text(String::from("Hello, World!")),
                &(
                    MenuItemType::Button(String::from("Start Game")),
                    OnPressAction::Multiple(vec![
                        OnPressAction::DispatchSystem(start_game_state),
                        OnPressAction::Close,
                    ]),
                ),
                &(
                    MenuItemType::Button(String::from("Settings")),
                    OnPressAction::NavigateTo(CurrentMenu::Settings),
                ),
            ]),
        )
        .add_menu(
            CurrentMenu::Settings,
            Menu::new()
                .add_items(&[&MenuItemType::Text(String::from("Settings"))])
                .add_items_positioned(
                    ItemPosition::SouthEast,
                    &[&(
                        MenuItemType::Button(String::from("Back")),
                        OnPressAction::NavigateTo(CurrentMenu::MainMenu),
                    )],
                ),
        );

    dbg!(&plugin);
    app.add_plugins(plugin);
}
