"""ChatPane - an individual chat pane with its own session/model.

This widget encapsulates the main chat area (header, messages, input) and can be
used standalone or in a split-pane layout for comparing different models.
"""

from typing import TYPE_CHECKING, Any

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

from cli.tui.chat.store import ChatStore
from cli.tui.chat.widgets.chat_header import ChatHeader
from cli.tui.chat.widgets.chat_input import ChatInput
from cli.tui.chat.widgets.injection_popup import InjectionSuggestionPopup
from cli.tui.chat.widgets.message_display import MessageDisplay

if TYPE_CHECKING:
    pass


class ChatPane(Widget):
    """Individual chat pane with its own session/model.

    This widget contains the main chat interface components:
    - ChatHeader: Shows current session/model info
    - MessageDisplay: Shows message history and pending request state
    - ChatInput: Text input for composing messages

    Each pane has its own ChatStore, allowing independent sessions
    or the same session with different views.

    Usage:
        # Single pane
        pane = ChatPane(store=my_store, pane_id="main")

        # Split panes for comparison
        left_pane = ChatPane(store=left_store, pane_id="left")
        right_pane = ChatPane(store=right_store, pane_id="right")
    """

    DEFAULT_CSS = """
    ChatPane {
        width: 1fr;
        height: 100%;
    }
    
    ChatPane.focused-pane {
        border: tall $accent;
    }
    
    ChatPane.unfocused-pane {
        border: tall $surface-darken-2;
    }
    
    ChatPane #pane-container {
        height: 100%;
    }
    """

    def __init__(
        self,
        store: ChatStore,
        pane_id: str = "main",
        show_border: bool = False,
        **kwargs: Any,
    ) -> None:
        """Initialize the chat pane.

        Args:
            store: ChatStore instance for state management.
            pane_id: Unique identifier for this pane (e.g., "left", "right", "main").
            show_border: Whether to show a border around the pane (for split view).
        """
        super().__init__(**kwargs)
        self._store = store
        self._pane_id = pane_id
        self._show_border = show_border

    @property
    def pane_id(self) -> str:
        """Get the pane identifier."""
        return self._pane_id

    @property
    def store(self) -> ChatStore:
        """Get the pane's ChatStore."""
        return self._store

    def compose(self) -> ComposeResult:
        """Compose the pane layout."""
        with Vertical(id="pane-container"):
            yield ChatHeader(self._store)
            yield MessageDisplay(self._store)
            # Popup is positioned here (above ChatInput) so it can float over messages
            yield InjectionSuggestionPopup(id="injection-popup")
            yield ChatInput(self._store)

    def on_mount(self) -> None:
        """Apply border styling based on configuration."""
        if self._show_border:
            self.add_class("unfocused-pane")

    def set_focused(self, focused: bool) -> None:
        """Update the pane's focused state (visual indicator).

        Args:
            focused: Whether this pane is the active/focused pane.
        """
        if not self._show_border:
            return

        if focused:
            self.remove_class("unfocused-pane")
            self.add_class("focused-pane")
        else:
            self.remove_class("focused-pane")
            self.add_class("unfocused-pane")

    def set_show_border(self, show_border: bool) -> None:
        """Enable or disable border styling for the pane."""
        self._show_border = show_border
        if not show_border:
            self.remove_class("focused-pane")
            self.remove_class("unfocused-pane")

    def focus_input(self) -> None:
        """Focus the chat input in this pane."""
        chat_input = self.query_one(ChatInput)
        chat_input.focus_input()

    def clear_input(self) -> None:
        """Clear the chat input in this pane."""
        chat_input = self.query_one(ChatInput)
        chat_input.clear_input()

    def get_input_text(self) -> str:
        """Get the current text from the chat input."""
        chat_input = self.query_one(ChatInput)
        return chat_input.get_text()
