use std::{
    io::{self, Write},
    num::NonZeroU32,
    time::Duration,
};

use crossterm::{
    cursor::MoveTo,
    event::{
        self, Event, KeyCode, KeyEvent,
        KeyEventKind::{Press, Repeat},
        KeyModifiers,
    },
    style::{Print, PrintStyledContent, Stylize},
    terminal::{Clear, ClearType},
    QueueableCommand,
};
use falling_tetromino_engine::{
    DelayParameters, ExtDuration, ExtNonNegF64, Game, GameLimits, InGameTime, Stat,
};

use crate::{
    application::{
        menus::{Menu, MenuUpdate},
        Application, GameMetaData, GameRestorationData, GameSave, GameplaySettings, Glyphset,
        NewGameSettings, UncompressedInputHistory,
    },
    fmt_helpers::{fmt_button_input, fmt_duration, fmt_hertz, FmtBool},
    game_modes::{
        game_modifiers::{self, Combo},
        GameMode,
    },
    game_renderers::{Renderer, TetroTUIRenderer},
};

impl<T: Write> Application<T> {
    pub(in crate::application) fn run_menu_new_game(&mut self) -> io::Result<MenuUpdate> {
        let mut selected = 0usize;
        let mut customization_selected = 0usize;

        let lowerbound_cheese = NonZeroU32::new(10).unwrap();
        let lowerbound_combo = NonZeroU32::new(10).unwrap();

        let d_time = Duration::from_secs(10);
        let d_score = 10;
        let d_pieces = 1;
        let d_lines = 1;

        let d_fall_delay = Duration::from_millis(100).into();
        let mult_fall_delay = ExtNonNegF64::from(10);
        let lowerbound_fall_delay: ExtDuration = Duration::from_millis(1).into();
        let upperbound_fall_delay: ExtDuration = Duration::from_secs(1000).into();

        loop {
            #[allow(clippy::type_complexity)]
            let mut game_modes = vec![
                GameMode::swift(),
                GameMode::classic(),
                GameMode::puzzle(),
                GameMode::cheese(
                    self.settings.new_game.cheese_tiles_per_line,
                    self.settings.new_game.cheese_limit,
                    self.settings.new_game.cheese_fall_lock_delays,
                ),
                GameMode::combo(
                    self.settings.new_game.combo_initial_layout,
                    self.settings.new_game.combo_limit,
                ),
            ];

            if self.settings.new_game.master_mode_unlocked {
                game_modes.insert(2, GameMode::master());
            }

            if self.settings.new_game.experimental_mode_unlocked {
                game_modes.push(GameMode::ascent())
            }

            // First part: rendering the menu.
            let w_main = Self::W_MAIN.into();
            let (x_main, y_main) = Self::fetch_main_xy();
            let y_selection = Self::H_MAIN / 5;
            let savepoint_available = if !self.game_saves.1.is_empty() { 1 } else { 0 };
            // Normal presets + 2 spaces if savepoint option available + custom preset.
            let selection_len = game_modes.len() + savepoint_available + 1;
            // There are four columns for the custom stat selection.
            let customization_selection_size = 4;
            selected %= selection_len;
            customization_selected %= customization_selection_size;
            // Render menu title.
            self.term
                .queue(Clear(ClearType::All))?
                .queue(MoveTo(x_main, y_main + y_selection))?
                .queue(PrintStyledContent(
                    format!("{:^w_main$}", "+ Start New Game +").bold(),
                ))?
                .queue(MoveTo(x_main, y_main + y_selection + 2))?
                .queue(Print(format!("{:^w_main$}", "──────────────────────────")))?;
            // Render normal and special gamemodes.
            for (
                i,
                GameMode {
                    title,
                    description,
                    stat_and_order_desc: _,
                    build: _,
                },
            ) in game_modes.iter().enumerate()
            {
                self.term
                    .queue(MoveTo(
                        x_main,
                        y_main + y_selection + 4 + u16::try_from(i).unwrap(),
                    ))?
                    .queue(Print(format!(
                        "{:^w_main$}",
                        if i == selected {
                            format!(">> {title}: {description} <<")
                        } else {
                            title.to_string()
                        }
                    )))?;
            }
            // Render load savepoint option.
            if let Some(GameSave {
                game_meta_data,
                game_restoration_data: GameRestorationData { input_history, .. },
                inputs_to_load,
            }) = &self.game_saves.1.get(self.game_saves.0)
            {
                let load_title = &game_meta_data.title;
                let load_offset_max = input_history.len();
                self.term
                    .queue(MoveTo(
                        x_main,
                        y_main + y_selection + 4 + u16::try_from(game_modes.len() + 1).unwrap(),
                    ))?
                    .queue(Print(format!(
                        "{:^w_main$}",
                        if selected == selection_len - 2 {
                            if *inputs_to_load == 0 {
                                format!(">> Load {load_title} from beginning [Del] <<")
                            } else {
                                let (load_time, load_input) = input_history[(inputs_to_load - 1) % input_history.len()];
                                let load_time = fmt_duration(load_time);
                                let load_input = fmt_button_input(load_input, self.settings.graphics().glyphset != Glyphset::Unicode);
                                format!(">> Load {load_title} from input {inputs_to_load}/{load_offset_max} ({load_input} @ {load_time}) [Del] <<")
                            }
                        } else {
                            format!("Savepoint ({load_title})")
                        },
                    )))?;
            }
            // Render custom mode option.
            self.term
                .queue(MoveTo(
                    x_main,
                    y_main
                        + y_selection
                        + 4
                        + u16::try_from(selection_len + savepoint_available).unwrap(),
                ))?
                .queue(Print(format!(
                    "{:^w_main$}",
                    if selected == selection_len - 1 {
                        format!(
                            "{:<42}",
                            format!(
                                "{} Custom: [Del]=reset{}{}",
                                if customization_selected == 0 {
                                    ">>"
                                } else {
                                    " |"
                                },
                                if self.settings.new_game.custom_seed.is_some() {
                                    " *seed"
                                } else {
                                    ""
                                },
                                if self.settings.new_game.custom_encoded_board.is_some() {
                                    " *board"
                                } else {
                                    ""
                                },
                            ),
                        )
                    } else {
                        "Custom".to_owned()
                    }
                )))?;
            // Render custom mode stuff.
            if selected == selection_len - 1 {
                let stats_strs = [
                    format!(
                        "| Initial fall delay = {:?}s (Gravity: {})",
                        self.settings
                            .new_game
                            .custom_fall_delay_params
                            .base_delay()
                            .as_secs_ennf64()
                            .get(),
                        fmt_hertz(
                            self.settings
                                .new_game
                                .custom_fall_delay_params
                                .base_delay()
                                .as_hertz()
                        ),
                    ),
                    format!(
                        "| Progressive gravity = {}",
                        (!self
                            .settings
                            .new_game
                            .custom_fall_delay_params
                            .is_constant())
                        .fmt_on_off()
                    ),
                    format!(
                        "| Limit = {:?} [→]",
                        self.settings.new_game.custom_win_condition
                    ),
                ];
                for (j, stat_str) in stats_strs.into_iter().enumerate() {
                    self.term
                        .queue(MoveTo(
                            x_main + 16 + 4 * u16::try_from(j).unwrap(),
                            y_main
                                + y_selection
                                + 4
                                + u16::try_from(1 + j + selection_len + savepoint_available)
                                    .unwrap(),
                        ))?
                        .queue(Print(if j + 1 == customization_selected {
                            format!(
                                ">{stat_str}{}",
                                if customization_selected != 3
                                    || self.settings.new_game.custom_win_condition.is_some()
                                {
                                    " [↓|↑]"
                                } else {
                                    ""
                                }
                            )
                        } else {
                            stat_str
                        }))?;
                }
            }
            self.term.flush()?;
            // Wait for new input.
            let mut immediately_start_new_game = false;
            match event::read()? {
                // Quit app.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('c' | 'C'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: Press | Repeat,
                    state: _,
                }) => break Ok(MenuUpdate::Push(Menu::Quit)),

                // Exit menu.
                Event::Key(KeyEvent {
                    code: KeyCode::Esc | KeyCode::Char('q' | 'Q') | KeyCode::Backspace,
                    kind: Press,
                    ..
                }) => break Ok(MenuUpdate::Pop),

                // Try select mode.
                Event::Key(KeyEvent {
                    code: KeyCode::Enter | KeyCode::Char('e' | 'E'),
                    kind: Press,
                    ..
                }) => {
                    // FIXME: Remove or reinstate code: Unused because replaying savepoint from this menu feels a bit out of place.
                    // if modifiers.contains(KeyModifiers::ALT) {
                    //     if let Some(GameSave {
                    //         game_meta_data,
                    //         game_restoration_data,
                    //         inputs_to_load: _,
                    //     }) = &self.game_saves.1.get(self.game_saves.0) {
                    //         let replay_length = if let Some((time, _)) = game_restoration_data.input_history.last() {
                    //             *time
                    //         } else {
                    //             Duration::ZERO
                    //         };
                    //         break Ok(MenuUpdate::Push(Menu::ReplayGame {
                    //             game_restoration_data: Box::new(game_restoration_data.clone()),
                    //             game_meta_data: game_meta_data.clone(),
                    //             replay_length,
                    //             game_renderer: Default::default(),
                    //         }))
                    //     }
                    // }
                    immediately_start_new_game = true;
                }

                // Move selector up or increase stat.
                Event::Key(KeyEvent {
                    code: KeyCode::Up | KeyCode::Char('k' | 'K'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if customization_selected > 0 {
                        match customization_selected {
                            1 => {
                                // Increase custom fall delay.
                                let base_delay =
                                    self.settings.new_game.custom_fall_delay_params.base_delay();

                                let new_base_delay = if base_delay.is_zero() {
                                    lowerbound_fall_delay.max(d_fall_delay)
                                } else if base_delay.is_infinite() {
                                    base_delay
                                } else {
                                    let new_base_delay = if modifiers.contains(KeyModifiers::ALT) {
                                        base_delay.mul_ennf64(mult_fall_delay)
                                    } else {
                                        base_delay + d_fall_delay
                                    };
                                    if new_base_delay > upperbound_fall_delay {
                                        ExtDuration::Infinite
                                    } else {
                                        new_base_delay
                                    }
                                };

                                let lowerbound =
                                    self.settings.new_game.custom_fall_delay_params.lowerbound();
                                self.settings.new_game.custom_fall_delay_params = self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .with_bounds(new_base_delay, lowerbound)
                                    .unwrap();
                            }
                            2 => {
                                // Toggle increasing fall delay.
                                let (new_factor, new_subtrahend) = if self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .is_constant()
                                {
                                    let d = DelayParameters::standard_fall();
                                    (d.factor(), d.subtrahend())
                                } else {
                                    let c = DelayParameters::constant(Default::default());
                                    (c.factor(), c.subtrahend())
                                };
                                self.settings.new_game.custom_fall_delay_params = self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .with_coefficients(new_factor, new_subtrahend)
                                    .unwrap();
                            }
                            3 => {
                                match self.settings.new_game.custom_win_condition {
                                    Some(Stat::TimeElapsed(ref mut t)) => {
                                        *t += d_time;
                                    }
                                    Some(Stat::PiecesLocked(ref mut p)) => {
                                        *p += d_pieces;
                                    }
                                    Some(Stat::LinesCleared(ref mut l)) => {
                                        *l += d_lines;
                                    }
                                    Some(Stat::PointsScored(ref mut s)) => {
                                        *s += d_score;
                                    }
                                    None => {}
                                };
                            }
                            _ => unreachable!(),
                        }
                    } else {
                        selected += selection_len - 1;
                    }
                }

                // Move selector down or decrease stat.
                Event::Key(KeyEvent {
                    code: KeyCode::Down | KeyCode::Char('j' | 'J'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    // Selected custom stat; decrease it.
                    if customization_selected > 0 {
                        match customization_selected {
                            1 => {
                                // Increase custom fall delay.
                                let base_delay =
                                    self.settings.new_game.custom_fall_delay_params.base_delay();

                                let new_base_delay = if base_delay.is_zero() {
                                    base_delay
                                } else if base_delay.is_infinite() {
                                    upperbound_fall_delay
                                } else {
                                    let new_base_delay = if modifiers.contains(KeyModifiers::ALT) {
                                        base_delay.div_ennf64(mult_fall_delay)
                                    } else {
                                        base_delay.saturating_sub(d_fall_delay)
                                    };
                                    if new_base_delay < lowerbound_fall_delay {
                                        ExtDuration::ZERO
                                    } else {
                                        new_base_delay
                                    }
                                };

                                let lowerbound =
                                    self.settings.new_game.custom_fall_delay_params.lowerbound();

                                self.settings.new_game.custom_fall_delay_params = self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .with_bounds(new_base_delay, lowerbound)
                                    .unwrap();
                            }
                            2 => {
                                // Toggle increasing fall delay.
                                let (new_factor, new_subtrahend) = if self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .is_constant()
                                {
                                    let d = DelayParameters::standard_fall();
                                    (d.factor(), d.subtrahend())
                                } else {
                                    let c = DelayParameters::constant(Default::default());
                                    (c.factor(), c.subtrahend())
                                };
                                self.settings.new_game.custom_fall_delay_params = self
                                    .settings
                                    .new_game
                                    .custom_fall_delay_params
                                    .with_coefficients(new_factor, new_subtrahend)
                                    .unwrap();
                            }
                            3 => {
                                match self.settings.new_game.custom_win_condition {
                                    Some(Stat::TimeElapsed(ref mut t)) => {
                                        *t = t.saturating_sub(d_time);
                                    }
                                    Some(Stat::PiecesLocked(ref mut p)) => {
                                        *p = p.saturating_sub(d_pieces);
                                    }
                                    Some(Stat::LinesCleared(ref mut l)) => {
                                        *l = l.saturating_sub(d_lines);
                                    }
                                    Some(Stat::PointsScored(ref mut s)) => {
                                        *s = s.saturating_sub(d_score);
                                    }
                                    None => {}
                                };
                            }
                            _ => unreachable!(),
                        }
                    // Move gamemode selector
                    } else {
                        selected += 1;
                    }
                }

                // Move selector left (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Left | KeyCode::Char('h' | 'H'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if selected == selection_len - 1 && customization_selected > 0 {
                        customization_selected += customization_selection_size - 1
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_CHEESE)
                    {
                        if let Some(limit) = self.settings.new_game.cheese_limit {
                            self.settings.new_game.cheese_limit = if limit > lowerbound_cheese {
                                NonZeroU32::try_from(limit.get() - 1).ok()
                            } else {
                                None
                            };
                        }
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_COMBO)
                    {
                        if modifiers.contains(KeyModifiers::ALT) {
                            let new_layout_idx = if let Some(i) = Combo::LAYOUTS
                                .iter()
                                .position(|lay| *lay == self.settings.new_game.combo_initial_layout)
                            {
                                let layout_cnt = Combo::LAYOUTS.len();
                                (i + layout_cnt - 1) % layout_cnt
                            } else {
                                0
                            };
                            self.settings.new_game.combo_initial_layout =
                                Combo::LAYOUTS[new_layout_idx];
                        } else if let Some(limit) = self.settings.new_game.combo_limit {
                            self.settings.new_game.combo_limit = if limit > lowerbound_combo {
                                NonZeroU32::try_from(limit.get() - 1).ok()
                            } else {
                                None
                            };
                        }
                    } else if let Some(GameSave {
                        game_restoration_data: GameRestorationData { input_history, .. },
                        inputs_to_load,
                        ..
                    }) = self.game_saves.1.get_mut(self.game_saves.0)
                    {
                        if selected == selection_len - 2 {
                            *inputs_to_load += input_history.len()
                                * if modifiers.contains(KeyModifiers::ALT) {
                                    20
                                } else {
                                    1
                                };
                            *inputs_to_load %= input_history.len() + 1;
                        }
                    }
                }

                // Move selector right (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Right | KeyCode::Char('l' | 'L'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    // If custom gamemode selected, allow incrementing stat selection.
                    if selected == selection_len - 1 {
                        // If reached last stat, cycle through stats for limit.
                        if customization_selected == customization_selection_size - 1 {
                            self.settings.new_game.custom_win_condition =
                                match self.settings.new_game.custom_win_condition {
                                    Some(Stat::TimeElapsed(_)) => Some(Stat::PointsScored(200)),
                                    Some(Stat::PointsScored(_)) => Some(Stat::PiecesLocked(100)),
                                    Some(Stat::PiecesLocked(_)) => Some(Stat::LinesCleared(40)),
                                    Some(Stat::LinesCleared(_)) => None,
                                    None => Some(Stat::TimeElapsed(Duration::from_secs(300))),
                                };
                        } else {
                            customization_selected += 1
                        }
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_CHEESE)
                    {
                        self.settings.new_game.cheese_limit =
                            if let Some(limit) = self.settings.new_game.cheese_limit {
                                limit.checked_add(1)
                            } else {
                                Some(lowerbound_cheese)
                            };
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_COMBO)
                    {
                        if modifiers.contains(KeyModifiers::ALT) {
                            let new_layout_idx = if let Some(i) = Combo::LAYOUTS
                                .iter()
                                .position(|lay| *lay == self.settings.new_game.combo_initial_layout)
                            {
                                let layout_cnt = Combo::LAYOUTS.len();
                                (i + 1) % layout_cnt
                            } else {
                                0
                            };
                            self.settings.new_game.combo_initial_layout =
                                Combo::LAYOUTS[new_layout_idx];
                        } else {
                            self.settings.new_game.combo_limit =
                                if let Some(limit) = self.settings.new_game.combo_limit {
                                    limit.checked_add(1)
                                } else {
                                    Some(lowerbound_combo)
                                };
                        }
                    } else if let Some(GameSave {
                        game_restoration_data: GameRestorationData { input_history, .. },
                        inputs_to_load,
                        ..
                    }) = self.game_saves.1.get_mut(self.game_saves.0)
                    {
                        if selected == selection_len - 2 {
                            *inputs_to_load += if modifiers.contains(KeyModifiers::ALT) {
                                20
                            } else {
                                1
                            };
                            *inputs_to_load %= input_history.len() + 1;
                        }
                    }
                }

                // Move selector right (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Delete | KeyCode::Char('d' | 'D'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if selected == selection_len - 1 {
                        self.settings.new_game.custom_seed = None;
                        self.settings.new_game.custom_encoded_board = None;
                        self.settings.new_game.custom_fall_delay_params =
                            DelayParameters::standard_fall();
                        self.settings.new_game.custom_win_condition = None;
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_CHEESE)
                    {
                        self.settings.new_game.cheese_limit =
                            NewGameSettings::default().cheese_limit;
                    } else if selected < game_modes.len()
                        && game_modes[selected]
                            .title
                            .starts_with(GameMode::TITLE_COMBO)
                    {
                        if modifiers.contains(KeyModifiers::ALT) {
                            self.settings.new_game.combo_initial_layout = Combo::LAYOUTS[0];
                        } else {
                            self.settings.new_game.combo_limit =
                                NewGameSettings::default().combo_limit;
                        }
                    } else if selected == selection_len - 2 {
                        self.game_saves.1.remove(self.game_saves.0);
                        self.game_saves.0 = 0;
                    }
                }

                Event::Key(KeyEvent {
                    code: KeyCode::Char(c @ '0'..='9'),
                    kind: Press | Repeat,
                    ..
                }) => {
                    let n = c.to_string().parse::<usize>().unwrap();
                    if n <= selection_len {
                        selected = if n == 0 { 10 - 1 } else { n - 1 };
                        immediately_start_new_game = true;
                    }
                }

                // Secret - This unlocks things.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('u' | 'U'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: Press | Repeat,
                    ..
                }) => {
                    self.settings.new_game.master_mode_unlocked = true;
                    self.settings.new_game.experimental_mode_unlocked = true;
                }

                // Other event: don't care.
                _ => {}
            }

            if immediately_start_new_game {
                let GameplaySettings {
                    rotation_system,
                    tetromino_generator,
                    piece_preview_count,
                    delayed_auto_shift,
                    auto_repeat_rate,
                    soft_drop_factor,
                    line_clear_duration,
                    spawn_delay,
                    allow_initial_actions,
                    double_tap_move_finesse: _,
                } = *self.settings.gameplay();

                let mut builder = Game::builder();

                builder
                    .rotation_system(rotation_system)
                    .tetromino_generator(tetromino_generator)
                    .piece_preview_count(piece_preview_count)
                    .delayed_auto_shift(delayed_auto_shift)
                    .auto_repeat_rate(auto_repeat_rate)
                    .soft_drop_factor(soft_drop_factor)
                    .line_clear_duration(line_clear_duration)
                    .spawn_delay(spawn_delay)
                    .allow_initial_actions(allow_initial_actions);

                let (game_meta_data, mut game, game_input_history) = if selected < game_modes.len()
                {
                    // Build one of the selected game modes.
                    let GameMode {
                        title,
                        description: _,
                        stat_and_order_desc,
                        build,
                    } = &game_modes[selected];

                    let preset_game = build(&builder);

                    let preset_game_meta_data = GameMetaData {
                        datetime: chrono::Utc::now().format("%Y-%m-%d_%H:%M").to_string(),
                        title: title.to_owned(),
                        comparison_stat: *stat_and_order_desc,
                    };

                    let fresh_input_history = UncompressedInputHistory::default();

                    (preset_game_meta_data, preset_game, fresh_input_history)
                } else if selected == selection_len - 2 {
                    // Load saved game.
                    // SAFETY: we an only get into this case if save exists!...
                    let GameSave {
                        game_meta_data,
                        game_restoration_data,
                        inputs_to_load,
                    } = &self.game_saves.1.get(self.game_saves.0).unwrap();

                    let restored_game = game_restoration_data.restore(*inputs_to_load);

                    let mut restored_game_meta_data = game_meta_data.clone();
                    // Mark restored game as such.
                    restored_game_meta_data.title.push('\'');

                    let restored_input_history = game_restoration_data
                        .input_history
                        .iter()
                        .take(*inputs_to_load)
                        .copied()
                        .collect();

                    (
                        restored_game_meta_data,
                        restored_game,
                        restored_input_history,
                    )
                } else {
                    // Build custom game.
                    let n = &self.settings.new_game;

                    builder
                        .fall_delay_params(n.custom_fall_delay_params)
                        .game_limits(match n.custom_win_condition {
                            Some(stat) => GameLimits::single(stat, true),
                            None => GameLimits::new(),
                        });

                    // Make lock delay decrease if fall delay was chosen to decrease.
                    if !n.custom_fall_delay_params.is_constant() {
                        builder.lock_delay_params(DelayParameters::standard_lock());
                    }

                    // Optionally load custom seed.
                    if let Some(seed) = n.custom_seed {
                        builder.seed(seed);
                    }

                    // Optionally load custom board.
                    let new_custom_game = if let Some(encoded_board) = &n.custom_encoded_board {
                        game_modifiers::StartBoard::build(&builder, encoded_board.clone())
                    // Otherwise just build a normal custom game.
                    } else {
                        builder.build()
                    };

                    let title = match n.custom_win_condition {
                        Some(stat) => match stat {
                            Stat::TimeElapsed(duration) => format!("Time-{}s", duration.as_secs()),
                            Stat::PiecesLocked(p) => format!("Pieces-{p}"),
                            Stat::LinesCleared(l) => format!("Lines-{l}"),
                            Stat::PointsScored(s) => format!("Score-{s}"),
                        },
                        None => "Limitless".to_owned(),
                    };

                    let custom_game_meta_data = GameMetaData {
                        datetime: chrono::Utc::now().format("%Y-%m-%d_%H:%M").to_string(),
                        title,
                        comparison_stat: (Stat::PointsScored(0), false),
                    };
                    let fresh_input_history = UncompressedInputHistory::default();
                    (custom_game_meta_data, new_custom_game, fresh_input_history)
                };
                // FIXME: Remove eventually.
                // let mut game = game;
                // game.modifiers.push(game_mode_presets::game_modifiers::print_fall_delay::modifier());
                // game.modifiers.push(game_mode_presets::game_modifiers::misc_modifiers::print_recency_tet_gen_stats::modifier());
                // game.modifiers.push(falling_tetromino_engine::Modifier { descriptor: "always_clear_board".to_owned(), mod_function: Box::new(|_c, _i, s, _m, _f| { s.board = Default::default(); })});

                let mut game_renderer =
                    TetroTUIRenderer::with_number(self.temp_data.renderernumber);

                // We do an initial update, which allows a piece to spawn and queue to get generated.
                // We do this so the renderer does not render a first frame when game is in its raw start state.
                if game.state().time.is_zero() {
                    match game.update(InGameTime::ZERO, None) {
                        Ok(msgs) => game_renderer.push_game_notification_feed(msgs),
                        // ?? but i didn't even do anything yet
                        Err(_update_game_error) => {}
                    }
                }

                self.statistics.total_new_games_started += 1;

                break Ok(MenuUpdate::Push(Menu::PlayGame {
                    game: game.into(),
                    game_input_history,
                    game_meta_data,
                    game_renderer: game_renderer.into(),
                }));
            }
        }
    }
}
