// src/modes/common/commands.rs
use crate::tui::terminal::core::TerminalCore;
use crate::state::app::state::AppState;
use crate::pages::routing::{Router, Page};
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: &mut AppState,
        router: &Router,
    ) -> Result<(bool, String)> {
        match action {
            "quit" => self.handle_quit(terminal, app_state, router).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: &mut AppState,
        router: &Router,
    ) -> Result<(bool, String)> {
        // Use router to check unsaved changes
        let has_unsaved = match &router.current {
            Page::Login(page) => page.state.has_unsaved_changes(),
            Page::Register(state) => state.has_unsaved_changes(),
            Page::Form(path) => app_state
                .form_state_for_path_ref(path)
                .map(|fs| fs.has_unsaved_changes())
                .unwrap_or(false),
            _ => false,
        };

        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()))
    }
}
