"""Docked chat panel for Foreman AI assistant."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.widget import Widget
from textual.widgets import Static, Input, Button, RichLog
from textual.containers import Horizontal
from textual.message import Message


class ChatPanel(Widget):
    """Bottom-docked panel for chatting with the Foreman via MCP tools."""

    class ChatSubmitted(Message):
        """User submitted a chat message."""

        def __init__(self, text: str) -> None:
            super().__init__()
            self.text = text

    def compose(self) -> ComposeResult:
        yield Static("Foreman Chat — Ask about OpenClaw setup", id="chat-header")
        yield RichLog(id="chat-log", wrap=True, highlight=True, markup=True)
        with Horizontal(id="chat-input-container"):
            yield Input(placeholder="Ask the Foreman...", id="chat-input")
            yield Button("Send", id="chat-send", variant="primary")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "chat-send":
            self._submit()

    def on_input_submitted(self, event: Input.Submitted) -> None:
        if event.input.id == "chat-input":
            self._submit()

    def _submit(self) -> None:
        inp = self.query_one("#chat-input", Input)
        text = inp.value.strip()
        if text:
            inp.value = ""
            self.add_user_message(text)
            self.post_message(self.ChatSubmitted(text))

    def add_user_message(self, msg: str) -> None:
        log = self.query_one("#chat-log", RichLog)
        log.write(f"[bold cyan]You:[/bold cyan] {msg}")

    def add_bot_message(self, msg: str) -> None:
        log = self.query_one("#chat-log", RichLog)
        log.write(f"[bold #f59e0b]Foreman:[/bold #f59e0b] {msg}")

    def add_system_message(self, msg: str) -> None:
        log = self.query_one("#chat-log", RichLog)
        log.write(f"[dim]{msg}[/dim]")
