"""Focusable label widget with arrow key navigation."""

from textual.events import Key
from textual.widgets import Label

from flux_networking_shared.tui.messages import FocusTabsRequested
from flux_networking_shared.tui.widgets.interface_group import FocusButtonsRequested


class FocusLabel(Label, can_focus=True):
    """Label that can receive focus and navigates with arrow keys."""

    DEFAULT_CSS = """
        FocusLabel {
            border: solid $primary;
            padding: 1 2 1 2;

            &.--highlight {
                border: double $primary;
                background: $panel;
            }
        }
    """

    def watch_has_focus(self, has_focus: bool) -> None:
        """Toggle highlight class based on focus state."""
        super().watch_has_focus(has_focus)
        self.set_class(has_focus, "--highlight")

    def on_key(self, event: Key) -> None:
        """Handle up/down navigation to tabs or buttons."""
        event_name = event.name

        if event_name not in ["up", "down"]:
            return

        event.stop()

        msg_cls = FocusTabsRequested if event_name == "up" else FocusButtonsRequested

        self.post_message(msg_cls())
