"""Chat header widget for displaying session info."""

from typing import Callable

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.widget import Widget
from textual.widgets import Static

from cli.tui.chat.store import ChatStore
from cli.tui.chat.types import ChatState


class ChatHeader(Widget):
    """Widget for displaying current session information.

    Shows:
        - Session name
        - Agent name (if configured)
        - Message count
    """

    def __init__(self, store: ChatStore) -> None:
        """Initialize the chat header.

        Args:
            store: ChatStore instance for state management.
        """
        super().__init__()
        self._store = store
        self._unsubscribe: Callable[[], None] | None = None

    def compose(self) -> ComposeResult:
        """Compose the header layout."""
        with Vertical(id="chat-header"):
            yield Static(
                "[bold]Select a session[/] or press [cyan]Ctrl+N[/] to start a new chat",
                id="session-info",
            )

    def on_mount(self) -> None:
        """Subscribe to store on mount."""
        self._unsubscribe = self._store.subscribe(self._on_state_change)

    def on_unmount(self) -> None:
        """Unsubscribe from store on unmount."""
        if self._unsubscribe:
            self._unsubscribe()

    def _on_state_change(self, state: ChatState) -> None:
        """React to store state changes."""
        session_info = self.query_one("#session-info", Static)

        if state.session is None:
            session_info.update(
                "[bold]Select a session[/] or press [cyan]Ctrl+N[/] to start a new chat"
            )
        else:
            name = state.session.session_name or "Untitled Chat"
            agent_info = (
                f" | Agent: {state.session.agent_name}"
                if state.session.agent_name
                else ""
            )
            msg_count = state.session.message_count
            session_info.update(
                f"[bold]{name}[/]{agent_info} | [dim]{msg_count} messages[/]"
            )

    def reset(self) -> None:
        """Reset header to default state."""
        session_info = self.query_one("#session-info", Static)
        session_info.update(
            "[bold]Select a session[/] or press [cyan]Ctrl+N[/] to start a new chat"
        )
