// src/modes/canvas/common_mode.rs

use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::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;
crate::pages::forms::logic::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},
};
use crate::pages::routing::{Router, Page};

pub async fn handle_core_action(
    action: &str,
    auth_state: &mut AuthState,
    grpc_client: &mut GrpcClient,
    auth_client: &mut AuthClient,
    terminal: &mut TerminalCore,
    app_state: &mut AppState,
    router: &mut Router,
) -> Result<EventOutcome> {
    match action {
        "save" => {
            match &mut router.current {
                Page::Login(state) => {
                    let message = login_save(auth_state, state, auth_client, app_state)
                        .await
                        .context("Login save action failed")?;
                    Ok(EventOutcome::Ok(message))
                }
                Page::Form(form_state) => {
                    let save_outcome = form_save(app_state, form_state, grpc_client)
                        .await
                        .context("Form 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))
                }
                _ => Ok(EventOutcome::Ok("Save not applicable".into())),
            }
        }
        "force_quit" => {
            terminal.cleanup()?;
            Ok(EventOutcome::Exit("Force exiting without saving.".to_string()))
        }
        "save_and_quit" => {
            let message = match &mut router.current {
                Page::Login(state) => {
                    login_save(auth_state, state, auth_client, app_state)
                        .await
                        .context("Login save and quit action failed")?
                }
                Page::Form(form_state) => {
                    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(),
                    }
                }
                _ => "Save not applicable".to_string(),
            };
            terminal.cleanup()?;
            Ok(EventOutcome::Exit(format!("{}. Exiting application.", message)))
        }
        "revert" => {
            match &mut router.current {
                Page::Login(state) => {
                    let message = login_revert(state, app_state).await;
                    Ok(EventOutcome::Ok(message))
                }
                Page::Register(state) => {
                    let message = register_revert(state, app_state).await;
                    Ok(EventOutcome::Ok(message))
                }
                Page::Form(form_state) => {
                    let message = form_revert(form_state, grpc_client)
                        .await
                        .context("Form revert action failed")?;
                    Ok(EventOutcome::Ok(message))
                }
                _ => Ok(EventOutcome::Ok("Revert not applicable".into())),
            }
        }
        _ => Ok(EventOutcome::Ok(format!("Core action not handled: {}", action))),
    }
}
