use crate::prelude::*;

pub(crate) struct CreditsPlugin;

impl Plugin for CreditsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(OnExit(GameState::Loading), init_credits_ui)
            .add_systems(OnEnter(GameState::Credits), update_credits);
    }
}

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

fn init_credits_ui(
    mut commands: Commands,
    tweaks_file: Res<tweak::GameTweaks>,
    tweaks: Res<Assets<tweak::Tweaks>>,
) {
    let tweak = tweaks.get(tweaks_file.handle.clone()).expect("Load tweaks");
    let button_handle = tweak.get_handle::<Image>("buttons_image_resting").unwrap();
    let font_handle = tweak.get_handle::<Font>("buttons_font").unwrap();

    commands
        .spawn((
            GameState::Credits,
            NodeBundle {
                style: Style {
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    justify_content: JustifyContent::Center,
                    align_items: AlignItems::Center,
                    position_type: PositionType::Absolute,
                    flex_direction: FlexDirection::Column,
                    ..default()
                },
                visibility: Visibility::Hidden,
                ..default()
            },
        ))
        .with_children(|parent| {
            parent
                .spawn((
                    Credits,
                    NodeBundle {
                        style: Style {
                            padding: UiRect::all(Val::Px(25.0)),
                            ..default()
                        },
                        background_color: Color::BLACK.with_a(0.9).into(),
                        ..default()
                    },
                ))
                .with_children(|parent| {
                    parent.spawn((
                        Credits,
                        TextBundle {
                            text: Text {
                                justify: JustifyText::Center,
                                sections: vec![],
                                ..default()
                            },
                            ..default()
                        },
                    ));
                });

            parent
                .spawn((
                    menu::ButtonAction(GameState::Play),
                    menu::ButtonAction(menu::MenuState::On),
                    ButtonBundle {
                        style: Style {
                            padding: UiRect::all(Val::Px(5.0)),
                            margin: UiRect::all(Val::Px(5.0)),
                            ..default()
                        },
                        image: UiImage {
                            texture: button_handle.clone(),
                            ..default()
                        },
                        ..default()
                    },
                ))
                .with_children(|parent| {
                    parent.spawn(TextBundle {
                        text: Text {
                            sections: vec![TextSection {
                                value: "B a c k".into(),
                                style: TextStyle {
                                    color: Color::WHITE,
                                    font_size: 12.0,
                                    font: font_handle.clone(),
                                },
                            }],
                            ..default()
                        },
                        style: Style {
                            margin: UiRect::all(Val::Px(20.0)),
                            ..default()
                        },
                        ..default()
                    });
                });
        });
}

fn update_credits(
    mut query: Query<&mut Text, With<Credits>>,
    tweaks: Res<Assets<tweak::Tweaks>>,
    tweaks_file: Res<tweak::GameTweaks>,
) {
    let tweak = tweaks
        .get(tweaks_file.handle.clone())
        .expect("Load tweakfile");

    query.iter_mut().for_each(|mut text| {
        let credits_text = tweak.get::<String>("credits_text").unwrap();
        text.sections = {
            credits_text
                .split('\n')
                .map(|l| TextSection {
                    value: format!("{}\n", l),
                    style: TextStyle { ..default() },
                })
                .collect()
        };
        debug!("Text sections: {:?}", text.sections);
    });
}
