"""Popup widget for injection autocomplete suggestions.

This is a "dumb" display widget - it shows suggestions and highlights one,
but all keyboard handling is done by ChatInput which controls this popup.
"""

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.widget import Widget
from textual.widgets import OptionList, Static
from textual.widgets.option_list import Option

from cli.tui.chat.services.injection import InjectionCompletion


class InjectionSuggestionPopup(Widget):
    """Display-only popup for autocomplete suggestions.

    This widget is controlled entirely by ChatInput:
    - ChatInput calls show_suggestions() to display options
    - ChatInput calls highlight_next/previous() to change selection
    - ChatInput calls get_selected() when user accepts
    - ChatInput calls hide() to close

    The popup never takes focus - input stays in the text area.
    """

    DEFAULT_CSS = """
    InjectionSuggestionPopup {
        display: none;
    }
    
    InjectionSuggestionPopup.visible {
        display: block;
    }
    """

    # This widget should never take focus
    can_focus = False

    def __init__(self, id: str | None = None) -> None:
        super().__init__(id=id)
        self._suggestions: list[InjectionCompletion] = []
        self._injection_type: str = ""
        self._filter_text: str = ""
        self._highlighted_index: int = 0

    def compose(self) -> ComposeResult:
        """Compose the popup layout."""
        with Vertical():
            yield Static("@fragment()", id="popup-header")
            yield Static(
                "[dim]Type to filter • Tab accept • ↑↓ navigate • Esc dismiss[/]",
                id="popup-hint",
            )
            yield OptionList(id="popup-list")
            yield Static("No matches found", id="empty-hint")

    def on_mount(self) -> None:
        """Initialize popup state."""
        self.query_one("#empty-hint", Static).display = False
        # Disable focus on the option list too
        self.query_one("#popup-list", OptionList).can_focus = False

    def show_suggestions(
        self,
        suggestions: list[InjectionCompletion],
        injection_type: str,
        filter_text: str = "",
    ) -> None:
        """Display suggestions in the popup.

        Args:
            suggestions: List of completion suggestions.
            injection_type: Type of injection (fragment, text, json, schema).
            filter_text: Current filter/partial identifier typed by user.
        """
        self._suggestions = suggestions
        self._injection_type = injection_type
        self._filter_text = filter_text
        self._highlighted_index = 0

        # Update header to show current input state
        header = self.query_one("#popup-header", Static)
        if filter_text:
            header.update(f"@{injection_type}([bold]{filter_text}[/bold])")
        else:
            header.update(f"@{injection_type}()")

        # Update option list
        option_list = self.query_one("#popup-list", OptionList)
        option_list.clear_options()

        empty_hint = self.query_one("#empty-hint", Static)

        if suggestions:
            for i, suggestion in enumerate(suggestions):
                label = (
                    f"{suggestion.display_name}  [dim]{suggestion.description}[/dim]"
                )
                option_list.add_option(Option(label, id=str(i)))

            option_list.display = True
            empty_hint.display = False
            option_list.highlighted = 0
        else:
            option_list.display = False
            empty_hint.display = True
            if filter_text:
                empty_hint.update(f"No matches for '{filter_text}'")
            else:
                empty_hint.update("No items available")

        self.add_class("visible")

    def hide(self) -> None:
        """Hide the popup."""
        self.remove_class("visible")
        self._suggestions = []
        self._filter_text = ""
        self._highlighted_index = 0

    @property
    def is_visible(self) -> bool:
        """Check if popup is currently visible."""
        return self.has_class("visible")

    @property
    def has_suggestions(self) -> bool:
        """Check if there are any suggestions to select."""
        return bool(self._suggestions)

    def highlight_next(self) -> None:
        """Move highlight to next suggestion."""
        if not self._suggestions:
            return
        if self._highlighted_index < len(self._suggestions) - 1:
            self._highlighted_index += 1
            option_list = self.query_one("#popup-list", OptionList)
            option_list.highlighted = self._highlighted_index

    def highlight_previous(self) -> None:
        """Move highlight to previous suggestion."""
        if not self._suggestions:
            return
        if self._highlighted_index > 0:
            self._highlighted_index -= 1
            option_list = self.query_one("#popup-list", OptionList)
            option_list.highlighted = self._highlighted_index

    def get_selected(self) -> InjectionCompletion | None:
        """Get the currently highlighted suggestion.

        Returns:
            The selected completion, or None if no suggestions.
        """
        if not self._suggestions:
            return None
        if 0 <= self._highlighted_index < len(self._suggestions):
            return self._suggestions[self._highlighted_index]
        return None
