use std::cell::RefCell;
use std::marker::PhantomData;

use adw::prelude::*;
use adw::subclass::prelude::*;
use gettextrs::gettext;
use glib::Properties;
use gtk::CompositeTemplate;
use gtk::glib;

use crate::model;

mod imp {
    use super::*;

    #[derive(Debug, Default, Properties, CompositeTemplate)]
    #[properties(wrapper_type = super::KeyValRow)]
    #[template(resource = "/com/github/marhkb/Pods/ui/view/key_val_row.ui")]
    pub(crate) struct KeyValRow {
        pub(super) bindings: RefCell<Vec<glib::Binding>>,

        #[property(get, set = Self::set_key_val, construct)]
        pub(super) key_val: RefCell<Option<model::KeyVal>>,

        #[property(get = Self::key_placeholder_text, set = Self::set_key_placeholder_text, construct, nullable)]
        _key_placeholder_text: PhantomData<Option<String>>,
        #[property(get = Self::value_placeholder_text, set = Self::set_value_placeholder_text, construct, nullable)]
        _value_placeholder_text: PhantomData<Option<String>>,

        #[template_child]
        pub(super) key_entry: TemplateChild<gtk::Entry>,
        #[template_child]
        pub(super) value_entry: TemplateChild<gtk::Entry>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for KeyValRow {
        const NAME: &'static str = "PdsKeyValRow";
        type Type = super::KeyValRow;
        type ParentType = gtk::ListBoxRow;

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

            klass.install_action("key-val-row.remove", None, |widget, _, _| {
                if let Some(key_val) = widget.key_val() {
                    key_val.remove_request();
                }
            });
        }

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

    impl ObjectImpl for KeyValRow {
        fn properties() -> &'static [glib::ParamSpec] {
            Self::derived_properties()
        }

        fn set_property(&self, id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
            self.derived_set_property(id, value, pspec);
        }

        fn property(&self, id: usize, pspec: &glib::ParamSpec) -> glib::Value {
            self.derived_property(id, pspec)
        }
    }

    impl WidgetImpl for KeyValRow {}
    impl ListBoxRowImpl for KeyValRow {}

    #[gtk::template_callbacks]
    impl KeyValRow {
        fn key_placeholder_text(&self) -> Option<String> {
            self.key_entry.placeholder_text().map(Into::into)
        }

        fn set_key_placeholder_text(&self, value: Option<&str>) {
            self.key_entry.set_placeholder_text(value);
        }

        fn value_placeholder_text(&self) -> Option<String> {
            self.value_entry.placeholder_text().map(Into::into)
        }

        fn set_value_placeholder_text(&self, value: Option<&str>) {
            self.value_entry.set_placeholder_text(value);
        }

        #[template_callback]
        fn on_key_entry_changed(&self) {
            self.obj().notify("key-placeholder-text");
        }

        #[template_callback]
        fn on_value_entry_changed(&self) {
            self.obj().notify("value-placeholder-text");
        }

        pub(super) fn set_key_val(&self, value: Option<model::KeyVal>) {
            let obj = &*self.obj();
            if obj.key_val() == value {
                return;
            }

            let mut bindings = self.bindings.borrow_mut();

            while let Some(binding) = bindings.pop() {
                binding.unbind();
            }

            if let Some(ref key_val) = value {
                let binding = key_val
                    .bind_property("key", &*self.key_entry, "text")
                    .flags(glib::BindingFlags::SYNC_CREATE | glib::BindingFlags::BIDIRECTIONAL)
                    .build();
                bindings.push(binding);

                let binding = key_val
                    .bind_property("value", &*self.value_entry, "text")
                    .flags(glib::BindingFlags::SYNC_CREATE | glib::BindingFlags::BIDIRECTIONAL)
                    .build();
                bindings.push(binding);
            }

            self.key_val.replace(value);
        }
    }
}

glib::wrapper! {
    pub(crate) struct KeyValRow(ObjectSubclass<imp::KeyValRow>)
        @extends gtk::Widget, gtk::ListBoxRow,
        @implements gtk::Accessible, gtk::Actionable, gtk::Buildable, gtk::ConstraintTarget;
}

impl From<&model::KeyVal> for KeyValRow {
    fn from(key_val: &model::KeyVal) -> Self {
        KeyValRow::new(&gettext("Key"), &gettext("Value"), key_val)
    }
}

impl KeyValRow {
    pub fn new(
        key_placeholder_text: &str,
        value_placeholder_text: &str,
        entry: &model::KeyVal,
    ) -> Self {
        glib::Object::builder()
            .property("key-val", entry)
            .property("key-placeholder-text", key_placeholder_text)
            .property("value-placeholder-text", value_placeholder_text)
            .build()
    }
}
