"""Full-screen agent chat panel for Agent Johnny 5."""

from __future__ import annotations

import asyncio

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

from easyclaw_tui.messages import ChatSubmitted


class ConfirmWidget(Widget):
    """Inline confirmation widget for agent's ask_user tool."""

    class Responded(Message):
        """User clicked Approve or Deny."""

        def __init__(self, approved: bool) -> None:
            super().__init__()
            self.approved = approved

    def __init__(
        self,
        question: str,
        response_event: asyncio.Event,
        response_holder: list[str],
    ) -> None:
        super().__init__()
        self.question = question
        self._event = response_event
        self._holder = response_holder

    def compose(self) -> ComposeResult:
        yield Static(
            f"[bold #f59e0b]Johnny 5 wants to:[/bold #f59e0b]\n{self.question}",
            id="confirm-question",
        )
        with Horizontal(id="confirm-buttons"):
            yield Button("Approve", id="confirm-approve", variant="success")
            yield Button("Deny", id="confirm-deny", variant="error")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "confirm-approve":
            self._holder.append("approved")
        else:
            self._holder.append("denied")
        self._event.set()
        self.remove()


class AgentChatPanel(Widget):
    """Full-screen agent chat panel — primary UI for Agent Johnny 5."""

    def compose(self) -> ComposeResult:
        yield Static(
            " Agent Johnny 5 — Your AI Admin for OpenClaw",
            id="chat-header",
        )
        yield RichLog(id="chat-log", wrap=True, highlight=True, markup=True)
        yield Vertical(id="confirm-area")
        with Horizontal(id="chat-input-container"):
            yield Input(placeholder="Ask Johnny 5...", id="chat-input")
            yield Button("Send", id="chat-send", variant="primary")

    def on_mount(self) -> None:
        # Focus the input immediately
        self.query_one("#chat-input", Input).focus()

    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 not text:
            return

        inp.value = ""
        self.add_user_message(text)
        self.post_message(ChatSubmitted(text))

    # ─── Message Display Methods ─────────────────────────

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

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

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

    def add_install_update(self, msg: str) -> None:
        """Show a compact install step update."""
        log = self.query_one("#chat-log", RichLog)
        log.write(f"[dim]{msg}[/dim]")

    def add_tool_indicator(self, name: str, args: dict) -> None:
        """Show an inline tool call indicator."""
        log = self.query_one("#chat-log", RichLog)
        if name == "run_command":
            cmd = args.get("command", "")
            log.write(f"[dim]  $ {cmd}[/dim]")
        elif name.startswith("mcp_"):
            short = name.replace("mcp_", "")
            log.write(f"[dim]  [mcp] {short}[/dim]")
        elif name == "ask_user":
            pass  # Handled by confirm widget
        elif name in ("read_file", "write_file", "edit_file"):
            path = args.get("path", "")
            log.write(f"[dim]  {name}: {path}[/dim]")
        else:
            log.write(f"[dim]  {name}[/dim]")

    def show_thinking(self) -> None:
        """Show a thinking indicator."""
        log = self.query_one("#chat-log", RichLog)
        log.write("[dim italic]  Johnny 5 is thinking...[/dim italic]")

    def show_confirm(
        self,
        question: str,
        event: asyncio.Event,
        holder: list[str],
    ) -> None:
        """Mount an inline confirmation widget."""
        area = self.query_one("#confirm-area", Vertical)
        widget = ConfirmWidget(question, event, holder)
        area.mount(widget)

    def set_input_enabled(self, enabled: bool) -> None:
        """Enable or disable the input area."""
        inp = self.query_one("#chat-input", Input)
        btn = self.query_one("#chat-send", Button)
        inp.disabled = not enabled
        btn.disabled = not enabled
