/* pull_dialog.rs
 *
 * Copyright 2026 Christian Kruse
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use adw::prelude::*;
use gettextrs::gettext;
use relm4::prelude::*;

use crate::git;

pub struct PullDialogInit {
    pub defaults: git::PullDefaults,
    pub parent_window: Option<gtk::Window>,
}

#[derive(Debug)]
pub enum PullDialogOutput {
    Confirmed(git::PullSettings),
    Cancelled,
}

pub struct PullDialog {
    remote_model: gtk::StringList,
    selected_idx: u32,
    defaults: git::PullDefaults,
}

#[relm4::component(pub)]
impl Component for PullDialog {
    type Init = PullDialogInit;
    type Input = ();
    type Output = PullDialogOutput;
    type CommandOutput = ();

    view! {
        #[root]
        gtk::Box {
            set_orientation: gtk::Orientation::Vertical,
            add_css_class: "gap-l",

            adw::PreferencesGroup {
                #[name = "remote_row"]
                adw::ComboRow {
                    set_title: &gettext("Remote"),
                    set_model: Some(&model.remote_model),
                    set_selected: model.selected_idx,
                },

                #[name = "branch_row"]
                adw::EntryRow {
                    set_title: &gettext("Branch"),
                    set_text: &model.defaults.suggested_remote_branch,
                },

                #[name = "rebase_row"]
                adw::SwitchRow {
                    set_title: &gettext("Rebase"),
                    set_active: model.defaults.rebase_default,
                },

                #[name = "prune_row"]
                adw::SwitchRow {
                    set_title: &gettext("Prune"),
                    set_subtitle: &gettext("Remove remote-tracking branches that no longer exist on the remote"),
                    set_active: false,
                },

                #[name = "fetch_tags_row"]
                adw::SwitchRow {
                    set_title: &gettext("Fetch tags"),
                    set_subtitle: &gettext("Fetch all tags from the remote"),
                    set_active: false,
                },

                #[name = "autostash_row"]
                adw::SwitchRow {
                    set_title: &gettext("Auto-stash"),
                    set_subtitle: &gettext("Stash uncommitted changes before pulling and restore them after"),
                    set_active: model.defaults.dirty,
                    set_visible: model.defaults.dirty,
                },
            },
        }
    }

    fn init(init: Self::Init, root: Self::Root, sender: ComponentSender<Self>) -> ComponentParts<Self> {
        let defaults = init.defaults;

        let remote_model = gtk::StringList::new(&[]);
        let mut selected_idx = 0u32;
        for (i, remote) in defaults.remotes.iter().enumerate() {
            remote_model.append(remote);

            if *remote == defaults.suggested_remote {
                selected_idx = i as u32;
            }
        }

        let model = PullDialog {
            remote_model,
            selected_idx,
            defaults,
        };

        let widgets = view_output!();

        let dialog = adw::AlertDialog::builder().heading(gettext("Pull")).build();
        dialog.set_extra_child(Some(&root));

        dialog.add_response("cancel", &gettext("Cancel"));
        dialog.add_response("confirm", &gettext("Pull"));
        dialog.set_response_appearance("confirm", adw::ResponseAppearance::Suggested);
        dialog.set_default_response(Some("confirm"));
        dialog.set_close_response("cancel");

        let remote_model_ref = model.remote_model.clone();
        let remote_row = widgets.remote_row.clone();
        let branch_row = widgets.branch_row.clone();
        let rebase_row = widgets.rebase_row.clone();
        let prune_row = widgets.prune_row.clone();
        let fetch_tags_row = widgets.fetch_tags_row.clone();
        let autostash_row = widgets.autostash_row.clone();

        dialog.connect_response(None, move |_dialog, response| {
            if response == "confirm" {
                let remote = remote_model_ref
                    .string(remote_row.selected())
                    .map(|s| s.to_string())
                    .unwrap_or_default();

                let branch = branch_row.text().trim().to_string();

                if !branch.is_empty() {
                    sender
                        .output(PullDialogOutput::Confirmed(git::PullSettings {
                            remote,
                            branch,
                            rebase: rebase_row.is_active(),
                            stash: autostash_row.is_active(),
                            prune: prune_row.is_active(),
                            fetch_tags: fetch_tags_row.is_active(),
                        }))
                        .ok();
                }
            } else {
                sender.output(PullDialogOutput::Cancelled).ok();
            }
        });

        dialog.present(init.parent_window.as_ref());

        ComponentParts { model, widgets }
    }
}
