//! UI actions for viewing and editing deck metadata.
//!
//! This module owns deck-properties dialogs and the follow-up state repair
//! needed when shareable sync identity metadata changes.

use std::cell::RefCell;
use std::rc::Rc;

use crate::app_config::{CONFIG_PATH, forget_local_deck_sync_state_for_uuid};
use crate::app_state::AppState;
use crate::dialog_support::show_error_dialog_with_parent;
use crate::file_ops::portable_path;
use crate::ready_screen::{render, render_ready_screen_after_maintenance, sync_cards_menu_state};
use crate::review_dialogs::{
    DeckPropertiesEditorResult, show_deck_properties_dialog, show_deck_properties_editor_dialog,
};
use crate::review_ui::ReviewUi;

pub(crate) fn open_deck_properties_from_ui(ui: &ReviewUi, state: &Rc<RefCell<AppState>>) {
    let (localizer, details) = {
        let state_ref = state.borrow();
        (state_ref.localizer, state_ref.deck_properties_text())
    };

    show_deck_properties_dialog(ui.frame, localizer, &details);
}

pub(crate) fn edit_deck_properties_from_ui(ui: &ReviewUi, state: &Rc<RefCell<AppState>>) {
    let (localizer, metadata, previous_focus) = {
        let state_ref = state.borrow();
        (
            state_ref.localizer,
            state_ref.deck_metadata.clone(),
            state_ref
                .session
                .is_ready()
                .then(|| ui.current_ready_screen_focus())
                .flatten(),
        )
    };
    let Some(editor_result) = show_deck_properties_editor_dialog(ui.frame, localizer, &metadata)
    else {
        return;
    };
    let DeckPropertiesEditorResult {
        metadata,
        replaced_sync_deck_uuid,
    } = editor_result;

    let update_result = { state.borrow_mut().update_deck_metadata(metadata) };
    match update_result {
        Ok(()) => {
            if let Some(deck_uuid) = replaced_sync_deck_uuid
                && let Err(error) = forget_local_deck_sync_state_for_uuid(
                    portable_path(CONFIG_PATH),
                    &deck_uuid,
                    localizer,
                )
            {
                show_error_dialog_with_parent(
                    &ui.frame,
                    localizer.could_not_clear_local_sync_state_caption(),
                    &error,
                );
            }
            render_ready_screen_after_maintenance(ui, state, previous_focus);
            sync_cards_menu_state(ui, &state.borrow());
        }
        Err(error) => {
            show_error_dialog_with_parent(
                &ui.frame,
                localizer.could_not_edit_deck_properties_caption(),
                &error,
            );
            render(ui, &state.borrow());
        }
    }
}
