use crate::color::ColorRGBA;
use crate::main_window::MainWindow;
use glib::{Object, Properties, prelude::*, subclass::*};
use gtk4::{Accessible, Buildable, CompositeTemplate, ConstraintTarget, Widget, subclass::prelude::*};
use libadwaita::{Dialog, prelude::*, subclass::prelude::*};
use std::cell::RefCell;

mod imp {
    use super::*;

    #[derive(Debug, Default, CompositeTemplate, Properties)]
    #[properties(wrapper_type = super::AddTagDialog)]
    #[template(file = "data/resources/ui_templates/add_dialog/tag.blp")]
    pub struct AddTagDialog {
        #[property(get, set)]
        pub title: RefCell<String>,
    }

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

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

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

    #[glib::derived_properties]
    impl ObjectImpl for AddTagDialog {}

    impl WidgetImpl for AddTagDialog {}

    impl AdwDialogImpl for AddTagDialog {}

    #[gtk4::template_callbacks]
    impl AddTagDialog {
        #[template_callback]
        fn on_add_tag_clicked(&self) {
            let rgba = ColorRGBA::new(25, 220, 114, 1);
            let color = rgba.as_string_no_alpha();
            let title = self.title.borrow().to_string();

            if !title.is_empty() {
                let variant = (color, title).to_variant();
                MainWindow::activate_action("add-tag", Some(&variant));
                self.obj().close();
            }
        }

        #[template_callback]
        fn on_title_activated(&self) {
            if !self.title.borrow().is_empty() {
                self.on_add_tag_clicked();
            }
        }

        #[template_callback]
        fn is_string_not_empty(&self, string: String) -> bool {
            !string.is_empty()
        }
    }
}

glib::wrapper! {
    pub struct AddTagDialog(ObjectSubclass<imp::AddTagDialog>)
        @extends Widget, Dialog,
        @implements Accessible, Buildable, ConstraintTarget;
}

impl Default for AddTagDialog {
    fn default() -> Self {
        Object::new::<Self>()
    }
}
