// src/modes/common/commands.rs
use crate::tui::terminal::core::TerminalCore;
use crate::state::app::state::AppState;
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
use canvas::canvas::CanvasState;
use anyhow::Result;

pub struct CommandHandler;

impl CommandHandler {
    pub fn new() -> Self {
        Self
    }

    pub async fn handle_command(
        &mut self,
        action: &str,
        terminal: &mut TerminalCore,
        app_state: &AppState,
        form_state: &FormState,
        login_state: &LoginState,
        register_state: &RegisterState,
    ) -> Result<(bool, String)> {
        match action {
            "quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
            "force_quit" => self.handle_force_quit(terminal).await,
            "save_and_quit" => self.handle_save_quit(terminal).await,
            _ => Ok((false, format!("Unknown command: {}", action))),
        }
    }

    async fn handle_quit(
        &self,
        terminal: &mut TerminalCore,
        app_state: &AppState,
        form_state: &FormState,
        login_state: &LoginState,
        register_state: &RegisterState,
    ) -> Result<(bool, String)> {
        // Use actual unsaved changes state instead of is_saved flag
        let has_unsaved = if app_state.ui.show_login {
            login_state.has_unsaved_changes()
        } else if app_state.ui.show_register {
            register_state.has_unsaved_changes()
        } else {
            form_state.has_unsaved_changes
        };

        if !has_unsaved {
            terminal.cleanup()?;
            Ok((true, "Exiting.".into()))
        } else {
            Ok((false, "No changes saved. Use :q! to force quit.".into()))
        }
    }

    async fn handle_force_quit(
        &self,
        terminal: &mut TerminalCore,
    ) -> Result<(bool, String)> {
        terminal.cleanup()?;
        Ok((true, "Force exiting without saving.".into()))
    }

    async fn handle_save_quit(
        &mut self,
        terminal: &mut TerminalCore,
    ) -> Result<(bool, String)> {
        terminal.cleanup()?;
        Ok((true, "State saved. Exiting.".into()))
    }
}
