use crate::{GameState, HEDZ_GREEN, loading_assets::UIAssets};
#[cfg(feature = "server")]
use crate::{global_observer, protocol::PlaySound};
use bevy::prelude::*;
use serde::{Deserialize, Serialize};

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

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

#[derive(Component, Reflect, Default, Serialize, Deserialize, PartialEq)]
pub struct CashResource {
    pub cash: i32,
}

#[derive(Event)]
pub struct CashCollectEvent;

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

    #[cfg(feature = "server")]
    global_observer!(app, on_cash_collect);
}

#[cfg(feature = "server")]
fn on_cash_collect(
    _trigger: Trigger<CashCollectEvent>,
    mut commands: Commands,
    mut cash: Single<&mut 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: Single<&CashResource, Changed<CashResource>>,
    text: Query<Entity, With<CashText>>,
    mut writer: TextUiWriter,
) {
    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(HEDZ_GREEN.into()),
        TextLayout::new_with_justify(JustifyText::Center),
        Node {
            position_type: PositionType::Absolute,
            bottom: Val::Px(40.0),
            left: Val::Px(100.0),
            ..default()
        },
    ));
}
