use crate::{GameState, global_observer, loading_assets::UIAssets, sounds::PlaySound};
use bevy::prelude::*;

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
#[require(Transform)]
pub struct Cash;

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct CashText;

#[derive(Resource, Reflect, Default)]
pub struct CashResource {
    pub cash: i32,
}

#[derive(Event)]
pub struct CashCollectEvent;

pub fn plugin(app: &mut App) {
    app.init_resource::<CashResource>();
    app.add_systems(OnEnter(GameState::Playing), setup);
    app.add_systems(
        Update,
        (rotate, update_ui).run_if(in_state(GameState::Playing)),
    );

    global_observer!(app, on_cash_collect);
}

fn on_cash_collect(
    _trigger: Trigger<CashCollectEvent>,
    mut commands: Commands,
    mut cash: ResMut<CashResource>,
) {
    commands.trigger(PlaySound::CashCollect);

    cash.cash += 100;
}

fn rotate(time: Res<Time>, mut query: Query<&mut Transform, With<Cash>>) {
    for mut transform in query.iter_mut() {
        transform.rotate(Quat::from_rotation_y(time.delta_secs()));
    }
}

fn update_ui(
    cash: Res<CashResource>,
    text: Query<Entity, With<CashText>>,
    mut writer: TextUiWriter,
) {
    if cash.is_changed() {
        let Some(text) = text.iter().next() else {
            return;
        };

        *writer.text(text, 0) = cash.cash.to_string();
    }
}

fn setup(mut commands: Commands, assets: Res<UIAssets>) {
    commands.spawn((
        Name::new("cash-ui"),
        Text::new("0"),
        TextShadow::default(),
        CashText,
        TextFont {
            font: assets.font.clone(),
            font_size: 34.0,
            ..default()
        },
        TextColor(Color::Srgba(Srgba::rgb(0., 1., 0.))),
        TextLayout::new_with_justify(JustifyText::Center),
        Node {
            position_type: PositionType::Absolute,
            bottom: Val::Px(40.0),
            left: Val::Px(100.0),
            ..default()
        },
    ));
}
