// src/dialog/functions.rs

use crate::dialog::DialogState;
use crate::state::app::state::AppState;
use crate::ui::handlers::context::DialogPurpose;

impl AppState {
    pub fn show_dialog(
        &mut self,
        title: &str,
        message: &str,
        buttons: Vec<String>,
        purpose: DialogPurpose,
    ) {
        self.ui.dialog.dialog_title = title.to_string();
        self.ui.dialog.dialog_message = message.to_string();
        self.ui.dialog.dialog_buttons = buttons;
        self.ui.dialog.dialog_active_button_index = 0;
        self.ui.dialog.purpose = Some(purpose);
        self.ui.dialog.is_loading = false;
        self.ui.dialog.dialog_show = true;
        self.ui.focus_outside_canvas = true;
    }

    pub fn show_loading_dialog(&mut self, title: &str, message: &str) {
        self.ui.dialog.dialog_title = title.to_string();
        self.ui.dialog.dialog_message = message.to_string();
        self.ui.dialog.dialog_buttons.clear();
        self.ui.dialog.dialog_active_button_index = 0;
        self.ui.dialog.purpose = None;
        self.ui.dialog.is_loading = true;
        self.ui.dialog.dialog_show = true;
        self.ui.focus_outside_canvas = true;
    }

    pub fn update_dialog_content(
        &mut self,
        message: &str,
        buttons: Vec<String>,
        purpose: DialogPurpose,
    ) {
        if self.ui.dialog.dialog_show {
            self.ui.dialog.dialog_message = message.to_string();
            self.ui.dialog.dialog_buttons = buttons;
            self.ui.dialog.dialog_active_button_index = 0;
            self.ui.dialog.purpose = Some(purpose);
            self.ui.dialog.is_loading = false;
        }
    }

    pub fn hide_dialog(&mut self) {
        self.ui.dialog.dialog_show = false;
        self.ui.dialog.dialog_title.clear();
        self.ui.dialog.dialog_message.clear();
        self.ui.dialog.dialog_buttons.clear();
        self.ui.dialog.dialog_active_button_index = 0;
        self.ui.dialog.purpose = None;
        self.ui.focus_outside_canvas = false;
        self.ui.dialog.is_loading = false;
    }

    pub fn next_dialog_button(&mut self) {
        if !self.ui.dialog.dialog_buttons.is_empty() {
            let next_index = (self.ui.dialog.dialog_active_button_index + 1)
                % self.ui.dialog.dialog_buttons.len();
            self.ui.dialog.dialog_active_button_index = next_index;
        }
    }

    pub fn previous_dialog_button(&mut self) {
        if !self.ui.dialog.dialog_buttons.is_empty() {
            let len = self.ui.dialog.dialog_buttons.len();
            let prev_index =
                (self.ui.dialog.dialog_active_button_index + len - 1) % len;
            self.ui.dialog.dialog_active_button_index = prev_index;
        }
    }

    pub fn get_active_dialog_button_label(&self) -> Option<&str> {
        self.ui.dialog
            .dialog_buttons
            .get(self.ui.dialog.dialog_active_button_index)
            .map(|s| s.as_str())
    }
}
