from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label


class SendInputModal(ModalScreen[str | None]):
    """Modal to send text input to an agent."""

    CSS = """
    SendInputModal {
        align: center middle;
    }
    #input-dialog {
        width: 70;
        height: auto;
        max-height: 14;
        border: thick $accent;
        background: $surface;
        padding: 1 2;
    }
    #input-dialog Label {
        margin-bottom: 1;
    }
    .btn-row {
        height: 3;
        align: right middle;
    }
    .btn-row Button {
        margin-left: 1;
    }
    """

    def __init__(self, workspace_title: str, **kwargs) -> None:
        super().__init__(**kwargs)
        self.workspace_title = workspace_title

    def compose(self) -> ComposeResult:
        with Vertical(id="input-dialog"):
            yield Label(f"[bold]Send input to:[/] {self.workspace_title}")
            yield Input(placeholder="Type your message...", id="msg-input")
            with Vertical(classes="btn-row"):
                yield Button("Send", variant="primary", id="btn-send")
                yield Button("Cancel", variant="default", id="btn-cancel")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-cancel":
            self.dismiss(None)
        elif event.button.id == "btn-send":
            text = self.query_one("#msg-input", Input).value.strip()
            self.dismiss(text if text else None)

    def on_input_submitted(self, event: Input.Submitted) -> None:
        self.query_one("#btn-send", Button).press()
