// src/modes/canvas/common_mode.rs

use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState, auth::AuthState};
use crate::state::app::state::AppState;
use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::form::SaveOutcome;
use anyhow::{Context, Result};
use crate::tui::functions::common::{
    form::{save as form_save, revert as form_revert},
    login::{save as login_save, revert as login_revert},
    register::{revert as register_revert},
};

pub async fn handle_core_action(
    action: &str,
    form_state: &mut FormState,
    auth_state: &mut AuthState,
    login_state: &mut LoginState,
    register_state: &mut RegisterState,
    grpc_client: &mut GrpcClient,
    auth_client: &mut AuthClient,
    terminal: &mut TerminalCore,
    app_state: &mut AppState,
) -> Result<EventOutcome> {
    match action {
        "save" => {
            if app_state.ui.show_login {
                let message = login_save(auth_state, login_state, auth_client, app_state).await.context("Login save action failed")?;
                Ok(EventOutcome::Ok(message))
            } else {
                let save_outcome = form_save(
                    app_state,
                    form_state,
                    grpc_client,
                ).await.context("Register save action failed")?;
                let message = match save_outcome {
                    SaveOutcome::NoChange => "No changes to save.".to_string(),
                    SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
                    SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
                };
                Ok(EventOutcome::DataSaved(save_outcome, message))
            }
        },
        "force_quit" => {
            terminal.cleanup()?;
            Ok(EventOutcome::Exit("Force exiting without saving.".to_string()))
        },
        "save_and_quit" => {
            let message = if app_state.ui.show_login {
                login_save(auth_state, login_state, auth_client, app_state).await.context("Login save n quit action failed")?
            } else {
                let save_outcome = form_save(
                    app_state,
                    form_state,
                    grpc_client,
                ).await?;
                match save_outcome {
                    SaveOutcome::NoChange => "No changes to save.".to_string(),
                    SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
                    SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
                }
            };
            terminal.cleanup()?;
            Ok(EventOutcome::Exit(format!("{}. Exiting application.", message)))
        },
        "revert" => {
            if app_state.ui.show_login {
                let message = login_revert(login_state, app_state).await;
                Ok(EventOutcome::Ok(message))
            } else if app_state.ui.show_register {
                let message = register_revert(register_state, app_state).await;
                Ok(EventOutcome::Ok(message))
            } else {
                let message = form_revert(
                    form_state,
                    grpc_client,
                ).await.context("Form revert x action failed")?;
                Ok(EventOutcome::Ok(message))
            }
        },
        _ => Ok(EventOutcome::Ok(format!("Core action not handled: {}", action))),
    }
}
