use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::atomic::Ordering;

use crate::commands::AppCommand;
use crate::state::{ConfirmAction, Modal, ScriptField};

use super::{InputContext, InputResult};

pub fn handle_script_page(ctx: &mut InputContext, key: KeyEvent) -> InputResult {
    if ctx.app.script_editor.focused {
        handle_focused(ctx, key)
    } else {
        handle_unfocused(ctx, key)
    }
}

fn handle_focused(ctx: &mut InputContext, key: KeyEvent) -> InputResult {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

    match (ctrl, key.code) {
        (_, KeyCode::Esc) => {
            ctx.dispatch(AppCommand::ScriptSave);
            ctx.app.script_editor.focused = false;
        }
        (true, KeyCode::Char('e')) => {
            ctx.dispatch(AppCommand::ScriptSave);
            ctx.dispatch(AppCommand::ScriptEvaluate);
        }
        (true, KeyCode::Char('s')) => {
            ctx.dispatch(AppCommand::ToggleScriptStack);
        }
        _ => {
            ctx.app.script_editor.editor.input(key);
        }
    }
    InputResult::Continue
}

fn handle_unfocused(ctx: &mut InputContext, key: KeyEvent) -> InputResult {
    match key.code {
        KeyCode::Enter => {
            ctx.app.script_editor.focused = true;
        }
        KeyCode::Char('q') if !ctx.app.plugin_mode => {
            ctx.dispatch(AppCommand::OpenModal(Modal::Confirm {
                action: ConfirmAction::Quit,
                selected: false,
            }));
        }
        KeyCode::Char(' ') if !ctx.app.plugin_mode => {
            ctx.dispatch(AppCommand::TogglePlaying);
            ctx.playing
                .store(ctx.app.playback.playing, Ordering::Relaxed);
        }
        KeyCode::Char('s') => super::open_save(ctx),
        KeyCode::Char('l') => super::open_load(ctx),
        KeyCode::Char('?') => {
            ctx.dispatch(AppCommand::OpenModal(Modal::KeybindingsHelp { scroll: 0 }));
        }
        KeyCode::Char('L') => {
            ctx.dispatch(AppCommand::OpenScriptModal(ScriptField::Length));
        }
        KeyCode::Char('S') => {
            ctx.dispatch(AppCommand::OpenScriptModal(ScriptField::Speed));
        }
        _ => {}
    }
    InputResult::Continue
}
