"""TANINUX — Top-Level App. Sidebar links, ContentSwitcher rechts."""
from __future__ import annotations

from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.reactive import reactive
from textual.theme import Theme
from textual.widgets import ContentSwitcher, Footer, Header, Static

from taninux import __version__
from taninux.core.theme import (
    BASE1, BASE2, BASE3, BASE4, BASE5,
    CHIKYU, FG_ALT, RED, SHINKAI, TAKE, UME, YORU, YUKI,
)
from taninux.pillars import PILLARS, by_key


MOUNTAIN_THEME = Theme(
    name="mountain-fuji",
    background=YORU,
    surface=YORU,
    panel=YORU,
    foreground=YUKI,
    primary=UME,
    secondary=SHINKAI,
    accent=BASE5,
    success=TAKE,
    warning=CHIKYU,
    error=RED,
    dark=True,
    variables={
        "footer-key-foreground": BASE5,
        "footer-key-background": YORU,
        "footer-description-foreground": BASE4,
        "footer-description-background": YORU,
        "footer-foreground": BASE4,
        "footer-background": YORU,
        "header-background": YORU,
        "header-foreground": UME,
        "border": BASE2,
        "border-blurred": BASE2,
        "primary-darken-1": BASE2,
        "primary-darken-2": BASE1,
    },
)


class Sidebar(Vertical):
    """Linke Pillar-Liste mit dem aktiv markierten Eintrag."""

    DEFAULT_CSS = f"""
    Sidebar {{
        width: 22;
        background: {YORU};
        padding: 1 1 1 2;
        border-right: vkey {BASE2};
    }}
    Sidebar Static {{
        background: {YORU};
    }}
    Sidebar #s-brand {{
        height: 2;
        padding-bottom: 1;
        color: {UME};
    }}
    Sidebar #s-version {{
        height: 1;
        color: {BASE4};
    }}
    Sidebar .pillar-row {{
        height: 2;
        padding: 0 0 0 0;
    }}
    """

    current: reactive[str] = reactive("")

    def compose(self) -> ComposeResult:
        yield Static(f"[{UME}]▲[/] [{UME}]TANINUX[/]", id="s-brand", markup=True)
        yield Static(f"[{BASE4}]v{__version__}  ·  fuji[/]", id="s-version", markup=True)
        yield Static("", id="s-gap")
        for p in PILLARS:
            yield Static("", id=f"row-{p.key}", classes="pillar-row", markup=True)

    def watch_current(self, _old: str, new: str) -> None:
        self._refresh_view()

    def on_mount(self) -> None:
        self._refresh_view()

    def _refresh_view(self) -> None:
        for p in PILLARS:
            row = self.query_one(f"#row-{p.key}", Static)
            is_active = (self.current == p.key)
            key_color = UME if is_active else BASE4
            label_color = YUKI if is_active else BASE5
            tagline_color = BASE5 if is_active else BASE4
            marker = "▶" if is_active else " "
            row.update(
                f"[{key_color}]{marker} {p.icon}  {p.label}[/]\n"
                f"[{tagline_color}]    {p.tagline}[/]"
            )


class TaninuxApp(App):
    """TANINUX — Linux maintenance & management TUI."""

    CSS = f"""
    Screen {{
        background: {YORU};
        color: {YUKI};
        layout: vertical;
    }}
    Header {{
        background: {YORU};
        color: {UME};
    }}
    HeaderIcon {{
        display: none;
    }}
    #root {{
        height: 1fr;
        background: {YORU};
    }}
    #content {{
        width: 1fr;
        background: {YORU};
    }}
    Footer {{
        background: {YORU};
        color: {BASE4};
    }}
    FooterKey {{
        background: {YORU};
        color: {BASE4};
    }}
    FooterKey > .footer-key--key {{
        background: {YORU};
        color: {BASE5};
    }}
    FooterKey > .footer-key--description {{
        background: {YORU};
        color: {BASE4};
    }}
    """

    BINDINGS = [
        Binding("o", "switch('o')", "overview"),
        Binding("p", "switch('p')", "packages"),
        Binding("m", "switch('m')", "maintain"),
        Binding("u", "switch('u')", "update"),
        Binding("b", "switch('b')", "bundles"),
        Binding("s", "switch('s')", "suggest"),
        Binding("f", "switch('f')", "flatpak"),
        Binding("k", "switch('k')", "kernel"),
        Binding("h", "switch('h')", "health"),
        Binding("q", "quit", "quit"),
    ]

    TITLE = "▲ TANINUX"
    SUB_TITLE = "fuji · linux maintenance"

    def __init__(self) -> None:
        super().__init__()
        self.register_theme(MOUNTAIN_THEME)
        self.theme = "mountain-fuji"
        self.current_pillar: str = PILLARS[0].key

    def compose(self) -> ComposeResult:
        yield Header(show_clock=False, icon="")
        with Horizontal(id="root"):
            yield Sidebar(id="sidebar")
            with ContentSwitcher(initial=PILLARS[0].key, id="content"):
                for p in PILLARS:
                    yield p.factory(id=p.key)
        yield Footer()

    def on_mount(self) -> None:
        sidebar = self.query_one(Sidebar)
        sidebar.current = self.current_pillar

    def action_switch(self, key: str) -> None:
        if by_key(key) is None:
            return
        self.current_pillar = key
        self.query_one("#content", ContentSwitcher).current = key
        self.query_one(Sidebar).current = key


def run() -> None:
    TaninuxApp().run()
