/* branch_info_box.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, ngettext};
use relm4::prelude::*;

use crate::git::BranchInfo;
use crate::ui_helpers::format_time;

pub struct BranchInfoBox {
    branch_info: Option<BranchInfo>,
}

#[derive(Debug)]
pub enum BranchInfoBoxMsg {
    ShowBranchInfo(BranchInfo),
    Clear,
}

impl BranchInfoBox {
    fn name(&self) -> String {
        self.branch_info.as_ref().map(|b| b.name.clone()).unwrap_or_default()
    }

    fn is_head(&self) -> bool {
        self.branch_info.as_ref().is_some_and(|b| b.is_head)
    }

    fn latest_commit_summary(&self) -> String {
        self.branch_info
            .as_ref()
            .map(|b| b.latest_commit_summary.clone())
            .unwrap_or_default()
    }

    fn author_line(&self) -> String {
        self.branch_info
            .as_ref()
            .map(|b| format!("{} · {}", b.latest_commit_author, format_time(b.latest_commit_time)))
            .unwrap_or_default()
    }

    fn has_upstream(&self) -> bool {
        self.branch_info.as_ref().is_some_and(|b| b.upstream_name.is_some())
    }

    fn upstream_line(&self) -> String {
        self.branch_info
            .as_ref()
            .and_then(|b| {
                b.upstream_name
                    .as_ref()
                    .map(|u| format!("{u}  ↑{} ↓{}", b.ahead, b.behind))
            })
            .unwrap_or_default()
    }

    fn commits_line(&self) -> String {
        self.branch_info
            .as_ref()
            .map(|b| {
                if b.total_commits_capped {
                    // Translators: {} is the (capped) commit count, e.g. "50000+ Commits"
                    gettext("{}+ Commits").replace("{}", &b.total_commits.to_string())
                } else {
                    format!("{} {}", b.total_commits, ngettext("Commit", "Commits", b.total_commits as u32),)
                }
            })
            .unwrap_or_default()
    }
}

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

    view! {
        gtk::Box {
            set_orientation: gtk::Orientation::Vertical,
            add_css_class: "card",
            add_css_class: "gap-xs",
            add_css_class: "mb-xs",
            #[watch]
            set_visible: model.branch_info.is_some(),

            gtk::Box {
                set_orientation: gtk::Orientation::Horizontal,
                add_css_class: "gap-m",
                add_css_class: "mt-l",
                add_css_class: "ms-l",
                add_css_class: "me-l",

                gtk::Label {
                    add_css_class: "title-4",
                    set_halign: gtk::Align::Start,
                    set_hexpand: true,
                    set_ellipsize: gtk::pango::EllipsizeMode::End,
                    set_use_markup: false,
                    #[watch]
                    set_label: &model.name(),
                },

                gtk::Label {
                    set_label: "HEAD",
                    add_css_class: "badge",
                    set_halign: gtk::Align::End,
                    #[watch]
                    set_visible: model.is_head(),
                },
            },

            gtk::Label {
                set_halign: gtk::Align::Start,
                set_wrap: true,
                set_wrap_mode: gtk::pango::WrapMode::Word,
                add_css_class: "ms-l",
                add_css_class: "me-l",
                add_css_class: "dim-label",
                set_use_markup: false,
                #[watch]
                set_label: &model.latest_commit_summary(),
            },

            gtk::Label {
                set_halign: gtk::Align::Start,
                add_css_class: "dim-label",
                add_css_class: "caption",
                add_css_class: "ms-l",
                add_css_class: "me-l",
                set_use_markup: false,
                #[watch]
                set_label: &model.author_line(),
            },

            gtk::Label {
                set_halign: gtk::Align::Start,
                add_css_class: "dim-label",
                add_css_class: "caption",
                add_css_class: "ms-l",
                add_css_class: "me-l",
                #[watch]
                set_visible: model.has_upstream(),
                #[watch]
                set_label: &model.upstream_line(),
            },

            gtk::Label {
                set_halign: gtk::Align::Start,
                add_css_class: "dim-label",
                add_css_class: "caption",
                add_css_class: "ms-l",
                add_css_class: "me-l",
                add_css_class: "mb-l",
                #[watch]
                set_label: &model.commits_line(),
            },
        }
    }

    fn init(_init: Self::Init, root: Self::Root, _sender: ComponentSender<Self>) -> ComponentParts<Self> {
        let model = BranchInfoBox { branch_info: None };
        let widgets = view_output!();
        ComponentParts { model, widgets }
    }

    fn update(&mut self, msg: Self::Input, _sender: ComponentSender<Self>, _root: &Self::Root) {
        match msg {
            BranchInfoBoxMsg::ShowBranchInfo(info) => {
                self.branch_info = Some(info);
            }

            BranchInfoBoxMsg::Clear => {
                self.branch_info = None;
            }
        }
    }
}
