// src/tui/functions/form.rs
use crate::state::pages::form::FormState;
use crate::services::grpc_client::GrpcClient;
use canvas::canvas::CanvasState;
use anyhow::{anyhow, Result};

pub async fn handle_action(
    action: &str,
    form_state: &mut FormState,
    _grpc_client: &mut GrpcClient,
    ideal_cursor_column: &mut usize,
) -> Result<String> {
    if form_state.has_unsaved_changes() {
        return Ok(
            "Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
                .to_string(),
        );
    }

    let total_count = form_state.total_count;

    match action {
        "previous_entry" => {
            // Only decrement if the current position is greater than the first record.
            // This prevents wrapping from 1 to total_count.
            // It also correctly handles moving from "New Entry" (total_count + 1) to the last record.
            if form_state.current_position > 1 {
                form_state.current_position -= 1;
                *ideal_cursor_column = 0;
            }
        }
        "next_entry" => {
            // Only increment if the current position is not yet at the "New Entry" stage.
            // The "New Entry" position is total_count + 1.
            // This allows moving from the last record to "New Entry", but stops there.
            if form_state.current_position <= total_count {
                form_state.current_position += 1;
                *ideal_cursor_column = 0;
            }
        }
        _ => return Err(anyhow!("Unknown form action: {}", action)),
    }

    Ok(String::new())
}
