import gi

gi.require_version("Gtk", "4.0")
from typing import Any, Dict

from gi.repository import Gtk


class SummaryView(Gtk.Box):
    # This page shows a summary of the selected changes

    def __init__(self):
        super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        for s in (
            self.set_margin_top,
            self.set_margin_bottom,
            self.set_margin_start,
            self.set_margin_end,
        ):
            s(6)

        title = Gtk.Label.new(_("Zusammenfassung"))
        title.add_css_class("title-2")
        title.set_halign(Gtk.Align.START)
        self.append(title)

        sc = Gtk.ScrolledWindow()
        sc.set_vexpand(True)
        sc.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        self.append(sc)

        # Container für die Liste, damit wir Abstände zum Rand haben
        list_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        list_container.set_margin_start(12)
        list_container.set_margin_end(12)
        list_container.set_margin_top(6)
        list_container.set_margin_bottom(12)
        sc.set_child(list_container)

        self.listbox = Gtk.ListBox()
        self.listbox.set_selection_mode(Gtk.SelectionMode.NONE)
        # Neue CSS Klasse für den modernen Look
        self.listbox.add_css_class("summary-card")
        self.listbox.add_css_class("boxed-list") # GTK4 Standard-Klasse für runde Ecken
        list_container.append(self.listbox)

        hint = Gtk.Label.new(
            _("Bitte prüfe die Angaben – klicke danach auf „Installieren“.")
        )
        hint.set_wrap(True)
        hint.set_halign(Gtk.Align.START)
        hint.set_margin_start(12)
        self.append(hint)

    def _clear(self):
        child = self.listbox.get_first_child()
        while child:
            self.listbox.remove(child)
            child = self.listbox.get_first_child()

    def update_summary_data(self, data: Dict[str, Any]):
        self._clear()
        if not data:
            self._add_row(_("Hinweis"), _("Keine Daten vorhanden."))
            return

        for key, val in data.items():
            text = self._value_to_text(val)
            self._add_row(str(key), text)

    def _value_to_text(self, v: Any) -> str:
        if v is None:
            return "—"
        if isinstance(v, (list, tuple)):
            return ", ".join(map(str, v)) if v else "—"
        if isinstance(v, dict):
            items = []
            for k, val in v.items():
                items.append(f"{k}: {val}")
            return "; ".join(items) if items else "—"
        return str(v)

    def _add_row(self, key: str, value: str):
        row = Gtk.ListBoxRow()
        # Row bekommt eigene CSS Klasse für Abstände
        row.add_css_class("summary-row")

        h = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=24)
        h.set_margin_top(16)    # Viel mehr Platz oben
        h.set_margin_bottom(16) # Viel mehr Platz unten
        h.set_margin_start(16)
        h.set_margin_end(16)

        # KEY (Links)
        l_key = Gtk.Label.new(key)
        l_key.set_xalign(0)
        l_key.set_valign(Gtk.Align.START) # Oben bündig bei mehrzeiligem Text
        l_key.add_css_class("summary-key")
        # Feste Breite für Keys, damit es sauber aussieht (ca. 30% der Breite)
        l_key.set_size_request(200, -1) 

        # VALUE (Rechts)
        l_val = Gtk.Label.new(value)
        l_val.set_xalign(0)
        l_val.set_valign(Gtk.Align.START)
        l_val.set_wrap(True)
        l_val.set_selectable(True)
        l_val.set_hexpand(True) # Nimmt den restlichen Platz
        l_val.add_css_class("summary-value")

        h.append(l_key)
        h.append(l_val)
        row.set_child(h)
        self.listbox.append(row)