"""Chat panel widget for Claude SDK interaction."""

from collections.abc import Callable

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.widgets import Input, RichLog


class ChatPanel(Vertical):
    """Chat interface for Claude SDK interaction.

    Supports both interrogation mode (Calf Raises) and execution output.

    Interface for sibling integration:
        add_message(role: str, content: str) - Add message to display
        on_submit: Callable[[str], None] - Callback when user submits
        clear_input() - Clear the input field
    """

    DEFAULT_CSS = """
    ChatPanel {
        height: 100%;
    }

    ChatPanel RichLog {
        height: 1fr;
        border: solid $panel;
        background: $surface;
        padding: 0 1;
        scrollbar-gutter: stable;
    }

    ChatPanel Input {
        dock: bottom;
        margin-top: 1;
    }
    """

    # Callback for when user submits a message
    on_submit: Callable[[str], None] | None = None

    def compose(self) -> ComposeResult:
        """Compose the chat log and input field."""
        yield RichLog(id="chat-log", wrap=True, highlight=True, markup=True)
        yield Input(placeholder="Type a message...", id="chat-input")

    def on_input_submitted(self, event: Input.Submitted) -> None:
        """Handle user input submission."""
        message = event.value.strip()
        if not message:
            return

        # Display user message
        self.add_message("user", message)

        # Clear input
        self.clear_input()

        # Invoke callback if registered
        if self.on_submit is not None:
            self.on_submit(message)

    def add_message(self, role: str, content: str) -> None:
        """Add a message to the chat display.

        Args:
            role: Message author - "user", "assistant", or "system"
            content: Message text
        """
        log = self.query_one("#chat-log", RichLog)

        if role == "user":
            log.write(f"[bold cyan]You:[/] {content}")
        elif role == "assistant":
            log.write(f"[bold green]Claude:[/] {content}")
        elif role == "system":
            log.write(f"[dim italic]{content}[/]")
        else:
            log.write(f"[bold]{role}:[/] {content}")

    def clear_input(self) -> None:
        """Clear the input field."""
        input_widget = self.query_one("#chat-input", Input)
        input_widget.value = ""

    def clear_history(self) -> None:
        """Clear the chat history."""
        log = self.query_one("#chat-log", RichLog)
        log.clear()
