"""Label and switch combo widget."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Horizontal
from textual.dom import NoMatches
from textual.reactive import var
from textual.widgets import Label, Switch


class LabelSwitch(Horizontal):
    """Horizontal container with a label and toggle switch."""

    DEFAULT_CSS = """
        LabelSwitch {
            height: auto;
            width: auto;

            & > Label {
                height: 3;
                content-align: center middle;
            }
        }
    """

    label = var("")
    value = var(False)

    def __init__(
        self, label: str, *, value: bool = True, id: str | None = None
    ) -> None:
        super().__init__(id=id)
        self._label = label
        self._value = value

    def compose(self) -> ComposeResult:
        yield Label(self._label)
        yield Switch(self._value)

    def on_mount(self) -> None:
        self.label = self._label
        self.value = self._value

    def on_switch_changed(self, event: Switch.Changed) -> None:
        """Sync reactive value when switch changes."""
        self.value = event.value

    def watch_label(self, old: str, new: str) -> None:
        if old == new:
            return

        self._label = new

        try:
            label = self.query_one(Label)
        except NoMatches:
            return

        label.update(new)

    def watch_value(self, old: bool, new: bool) -> None:
        if old == new:
            return

        self._value = new

        try:
            switch = self.query_one(Switch)
        except NoMatches:
            return

        switch.value = new
