// src/functions/modes/edit/add_logic_e.rs
use crate::state::pages::add_logic::AddLogicState;
use crate::state::pages::canvas_state::CanvasState;
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent};

pub async fn execute_edit_action(
    action: &str,
    key: KeyEvent, // Keep key for insert_char
    state: &mut AddLogicState,
    ideal_cursor_column: &mut usize,
) -> Result<String> {
    let mut message = String::new();

    match action {
        "next_field" => {
            let current_field = state.current_field();
            let next_field = (current_field + 1) % AddLogicState::INPUT_FIELD_COUNT;
            state.set_current_field(next_field);
            *ideal_cursor_column = state.current_cursor_pos();
            message = format!("Focus on field {}", state.fields()[next_field]);
        }
        "prev_field" => {
            let current_field = state.current_field();
            let prev_field = if current_field == 0 {
                AddLogicState::INPUT_FIELD_COUNT - 1
            } else {
                current_field - 1
            };
            state.set_current_field(prev_field);
            *ideal_cursor_column = state.current_cursor_pos();
            message = format!("Focus on field {}", state.fields()[prev_field]);
        }
        "delete_char_forward" => {
            let current_pos = state.current_cursor_pos();
            let current_input_mut = state.get_current_input_mut();
            if current_pos < current_input_mut.len() {
                current_input_mut.remove(current_pos);
                state.set_has_unsaved_changes(true);
                if state.current_field() == 1 { state.update_target_column_suggestions(); }
            }
        }
        "delete_char_backward" => {
            let current_pos = state.current_cursor_pos();
            if current_pos > 0 {
                let new_pos = current_pos - 1;
                state.get_current_input_mut().remove(new_pos);
                state.set_current_cursor_pos(new_pos);
                *ideal_cursor_column = new_pos;
                state.set_has_unsaved_changes(true);
                if state.current_field() == 1 { state.update_target_column_suggestions(); }
            }
        }
        "move_left" => {
            let current_pos = state.current_cursor_pos();
            if current_pos > 0 {
                let new_pos = current_pos - 1;
                state.set_current_cursor_pos(new_pos);
                *ideal_cursor_column = new_pos;
            }
        }
        "move_right" => {
            let current_pos = state.current_cursor_pos();
            let input_len = state.get_current_input().len();
            if current_pos < input_len {
                let new_pos = current_pos + 1;
                state.set_current_cursor_pos(new_pos);
                *ideal_cursor_column = new_pos;
            }
        }
        "insert_char" => {
            if let KeyCode::Char(c) = key.code {
                let current_pos = state.current_cursor_pos();
                state.get_current_input_mut().insert(current_pos, c);
                let new_pos = current_pos + 1;
                state.set_current_cursor_pos(new_pos);
                *ideal_cursor_column = new_pos;
                state.set_has_unsaved_changes(true);
                if state.current_field() == 1 {
                    state.update_target_column_suggestions();
                }
            }
        }
        "suggestion_down" => {
            if state.in_target_column_suggestion_mode && !state.target_column_suggestions.is_empty() {
                let current_selection = state.selected_target_column_suggestion_index.unwrap_or(0);
                let next_selection = (current_selection + 1) % state.target_column_suggestions.len();
                state.selected_target_column_suggestion_index = Some(next_selection);
            }
        }
        "suggestion_up" => {
             if state.in_target_column_suggestion_mode && !state.target_column_suggestions.is_empty() {
                let current_selection = state.selected_target_column_suggestion_index.unwrap_or(0);
                let prev_selection = if current_selection == 0 {
                    state.target_column_suggestions.len() - 1
                } else {
                    current_selection - 1
                };
                state.selected_target_column_suggestion_index = Some(prev_selection);
            }
        }
        "select_suggestion" => {
            if state.in_target_column_suggestion_mode {
                let mut selected_suggestion_text: Option<String> = None;

                if let Some(selected_idx) = state.selected_target_column_suggestion_index {
                    if let Some(suggestion) = state.target_column_suggestions.get(selected_idx) {
                        selected_suggestion_text = Some(suggestion.clone());
                    }
                }

                if let Some(suggestion_text) = selected_suggestion_text {
                    state.target_column_input = suggestion_text.clone();
                    state.target_column_cursor_pos = state.target_column_input.len();
                    *ideal_cursor_column = state.target_column_cursor_pos;
                    state.set_has_unsaved_changes(true);
                    message = format!("Selected column: '{}'", suggestion_text);
                }

                state.in_target_column_suggestion_mode = false;
                state.show_target_column_suggestions = false;
                state.selected_target_column_suggestion_index = None;
                state.update_target_column_suggestions();
            } else {
                let current_field = state.current_field();
                let next_field = (current_field + 1) % AddLogicState::INPUT_FIELD_COUNT;
                state.set_current_field(next_field);
                *ideal_cursor_column = state.current_cursor_pos();
                message = format!("Focus on field {}", state.fields()[next_field]);
            }
        }
        _ => {}
    }
    Ok(message)
}
