from __future__ import annotations

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label, Select

NEW_WORKSPACE = "__new__"
CUSTOM_CWD = "__custom__"


class LaunchAgentModal(ModalScreen[dict | None]):
    """Modal to launch a new Claude Code agent."""

    BINDINGS = [
        Binding("escape", "cancel", "Close", show=False),
    ]

    CSS = """
    LaunchAgentModal {
        align: center middle;
    }
    #launch-dialog {
        width: 70;
        height: auto;
        max-height: 28;
        border: thick $accent;
        background: $surface;
        padding: 1 2;
    }
    #launch-dialog Label {
        margin-bottom: 1;
    }
    #launch-dialog Input {
        margin-bottom: 1;
    }
    #launch-dialog Select {
        margin-bottom: 1;
    }
    #custom-cwd-input {
        display: none;
    }
    .btn-row {
        height: 3;
        align: right middle;
    }
    .btn-row Button {
        margin-left: 1;
    }
    """

    def __init__(self, workspace_names: list[str], cwds: list[str] | None = None, **kwargs) -> None:
        super().__init__(**kwargs)
        self.workspace_names = workspace_names
        self.cwds = cwds or []

    def compose(self) -> ComposeResult:
        with Vertical(id="launch-dialog"):
            yield Label("[bold]Launch Claude Code Agent[/]")
            yield Label("Workspace:")
            ws_options: list[tuple[str, str]] = [("+ New workspace", NEW_WORKSPACE)]
            ws_options += [(name, name) for name in self.workspace_names]
            yield Select(ws_options, value=NEW_WORKSPACE, id="ws-select", allow_blank=False)
            yield Label("Working directory:")
            cwd_options: list[tuple[str, str]] = []
            for cwd in self.cwds:
                from pathlib import Path
                short = cwd.replace(str(Path.home()), "~")
                cwd_options.append((short, cwd))
            cwd_options.append(("Enter manually...", CUSTOM_CWD))
            yield Select(cwd_options, value=self.cwds[0] if self.cwds else CUSTOM_CWD, id="cwd-select", allow_blank=False)
            yield Input(placeholder="~/repos/my-project", id="custom-cwd-input")
            yield Label("Prompt / Task:")
            yield Input(placeholder="Fix the auth bug in login.ts", id="prompt-input")
            with Horizontal(classes="btn-row"):
                yield Button("Cancel", variant="default", id="btn-cancel")
                yield Button("Launch", variant="primary", id="btn-launch")

    def on_mount(self) -> None:
        self._toggle_custom_cwd()

    def on_select_changed(self, event: Select.Changed) -> None:
        if event.select.id == "cwd-select":
            self._toggle_custom_cwd()

    def _toggle_custom_cwd(self) -> None:
        cwd_select = self.query_one("#cwd-select", Select)
        custom_input = self.query_one("#custom-cwd-input", Input)
        if cwd_select.value == CUSTOM_CWD:
            custom_input.styles.display = "block"
        else:
            custom_input.styles.display = "none"

    def action_cancel(self) -> None:
        self.dismiss(None)

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-cancel":
            self.dismiss(None)
        elif event.button.id == "btn-launch":
            ws_select = self.query_one("#ws-select", Select)
            cwd_select = self.query_one("#cwd-select", Select)
            ws_value = ws_select.value
            if cwd_select.value == CUSTOM_CWD:
                cwd = self.query_one("#custom-cwd-input", Input).value.strip()
            else:
                cwd = str(cwd_select.value)
            result = {
                "workspace": None if ws_value == NEW_WORKSPACE else ws_value,
                "cwd": cwd,
                "prompt": self.query_one("#prompt-input", Input).value.strip(),
            }
            self.dismiss(result)

    def on_input_submitted(self, event: Input.Submitted) -> None:
        if event.input.id == "prompt-input":
            self.query_one("#btn-launch", Button).press()
