// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::any::Any;

use glium::Frame;
use winit::event::Event;

use crate::app::{App, config::action::ActionEvent, state::{GameState, GameStateId, Status}};
use crate::app::gui::{GuiState, style::UiExt};

pub struct Title {
	gui_state: GuiState,
}

impl Title {
	pub fn new() -> Title {
		Title {
			gui_state: GuiState::new(),
		}
	}
}

impl GameState for Title {
	fn enable(&mut self, app: &mut App) {
		self.gui_state.enable(&mut app.gui);
	}

	fn push(&mut self, _app: &mut App, msg: Option<Box<dyn Any>>) {
		debug_assert!(msg.is_none());
	}

	fn disable(&mut self, _app: &mut App) {}

	fn action(&mut self, action: ActionEvent) {
		self.gui_state.action(action);
	}

	fn event(&mut self, app: &mut App, event: &Event<()>) {
		self.gui_state.event(app, event);
	}

	fn loop_iter(&mut self, app: &mut App, frame: &mut Frame) -> Status {
		enum Action {
			PlaySelection,
			Settings,
			About,
		}

		let mut action = None;

		let res = GuiState::update(&mut app.gui, "title", &app.window, |_ctx, ui| {
			ui.vertical_centered(|ui| {
				ui.h1("Spaceships").add();
				if ui.b1("Play").clicked() {
					action = Some(Action::PlaySelection);
				}
				ui.add_space(4.0);
				if ui.b1("Settings").clicked() {
					action = Some(Action::Settings);
				}
				ui.add_space(4.0);
				if ui.b1("About").clicked() {
					action = Some(Action::About);
				}
				ui.add_space(4.0);

				if ui.b1("Exit").clicked() {
					self.gui_state.exit();
				}
			});
		});
		self.gui_state.after_update(res);

		app.gui.render(&app.display, frame);

		match action {
			_ if self.gui_state.should_exit() => Status::PopState,
			Some(Action::PlaySelection) => Status::PushState(GameStateId::PlaySelection, None),
			Some(Action::Settings) => Status::PushState(GameStateId::Settings, None),
			Some(Action::About) => Status::PushState(GameStateId::About, None),
			None => Status::Ok,
		}
	}
}
