"""Command reference widget.

Displays all available commands with their aliases in a compact panel.
Docked to the right side with fixed width.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from rich.text import Text
from textual.containers import VerticalScroll
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Static

if TYPE_CHECKING:
    from textual.app import ComposeResult

    from unfamiliar.tui.themes import ThemeConfig
    from unfamiliar.tui.views import CommandInfo


class CommandReference(Widget):
    """Widget displaying available commands with themed aliases.

    Shows a list of commands in a compact format with themed aliases.
    Fixed width, docked right.

    Attributes:
        commands: Reactive list of CommandInfo to display.
        theme: Theme configuration for vocabulary and aliases.

    Note: Styling is defined in noir.tcss, not DEFAULT_CSS, to use theme variables.
    """

    commands: reactive[list[CommandInfo]] = reactive([])

    def __init__(
        self,
        theme: ThemeConfig,
        commands: list[CommandInfo] | None = None,
        *,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        """Initialize the command reference widget.

        Args:
            theme: Theme configuration for vocabulary and aliases.
            commands: Initial list of commands to display.
            name: Widget name.
            id: Widget ID.
            classes: Space-separated CSS classes.
        """
        super().__init__(name=name, id=id, classes=classes)
        self.theme = theme
        self.commands = commands or []

    def _c(self, key: str) -> str:
        """Shorthand for self.theme.color(key)."""
        return self.theme.color(key)

    def compose(self) -> ComposeResult:
        """Compose the command reference layout."""
        # Header with decorative divider
        yield Static(
            Text("Commands", style=f"bold {self._c('accent')}"),
            classes="command-title",
        )
        yield Static(
            Text(self.theme.decoration("divider"), style=self._c("text_dim")),
            classes="command-divider",
        )
        yield VerticalScroll(id="command-list")

    def _update_children(self) -> None:
        """Update the command list with current data."""
        list_container = self.query_one("#command-list", VerticalScroll)
        # Remove existing command entries
        list_container.remove_children()

        # Add command entries: alias (bold) + description (dim)
        for cmd in self.commands:
            entry = Static(classes="command-entry")
            text = Text()
            # Show themed alias prominently
            text.append(cmd.alias, style=f"bold {self._c('accent')}")
            text.append("\n")
            # Show description on second line
            text.append(f"  {cmd.description}", style=f"dim {self._c('text_dim')}")
            entry.update(text)
            list_container.mount(entry)

    def watch_commands(
        self, old_commands: list[CommandInfo], new_commands: list[CommandInfo]
    ) -> None:
        """React to command list changes."""
        self.call_after_refresh(self._update_children)

    def on_mount(self) -> None:
        """Render initial data on mount."""
        # Defer render until children are mounted
        # (parent on_mount fires before children exist)
        self.call_after_refresh(self._update_children)

    def update_commands(self, commands: list[CommandInfo]) -> None:
        """Update the command list.

        Args:
            commands: New list of commands to display.
        """
        self.commands = commands


__all__ = ["CommandReference"]
