use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};

use crate::utils::error::DisplayError;

mod imp {
    use super::*;

    #[derive(Debug, Default, CompositeTemplate)]
    #[template(file = "create_collection_dialog.ui")]
    pub struct KrCreateCollectionDialog {
        #[template_child]
        entry_row: TemplateChild<adw::EntryRow>,
        #[template_child]
        stack: TemplateChild<gtk::Stack>,
        #[template_child]
        spinner: TemplateChild<gtk::Spinner>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for KrCreateCollectionDialog {
        const NAME: &'static str = "KrCreateCollectionDialog";
        type Type = super::KrCreateCollectionDialog;
        type ParentType = adw::Dialog;

        fn class_init(klass: &mut Self::Class) {
            klass.bind_template();
            klass.bind_template_callbacks();
        }

        fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
            obj.init_template();
        }
    }

    impl ObjectImpl for KrCreateCollectionDialog {}

    impl WidgetImpl for KrCreateCollectionDialog {}

    impl AdwDialogImpl for KrCreateCollectionDialog {}

    #[gtk::template_callbacks]
    impl KrCreateCollectionDialog {
        #[template_callback]
        async fn on_clicked(&self) {
            let name = &self.entry_row.text();
            if name.trim().is_empty() {
                self.entry_row.add_css_class("error");
                return;
            }

            self.obj().set_can_close(false);
            self.stack.set_visible_child(&*self.spinner);

            crate::app()
                .secret_service()
                .create_collection(name.trim())
                .await
                .handle_error("Unable to create keyring");

            self.obj().force_close();
        }
    }
}

glib::wrapper! {
    pub struct KrCreateCollectionDialog(ObjectSubclass<imp::KrCreateCollectionDialog>)
        @extends gtk::Widget, adw::Dialog;
}

impl KrCreateCollectionDialog {
    pub fn new() -> Self {
        glib::Object::new()
    }
}
