"""Modal dialog for creating a new watch."""

import httpx
from textual import work
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Container, Horizontal
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label, Select, Static

SENIORITY_OPTIONS = [
    ("Any", ""),
    ("Senior", "senior"),
    ("Mid", "mid"),
    ("Junior", "junior"),
]


class WatchCreateModal(ModalScreen[bool]):
    """Collects watch parameters and creates a watch via the API."""

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

    DEFAULT_CSS = """
    WatchCreateModal {
        align: center middle;
        background: $surface 80%;
    }

    #watch-modal-container {
        width: 60;
        height: auto;
        border: round $accent;
        padding: 1 2;
        background: $surface;
    }

    #watch-modal-title {
        text-align: center;
        padding: 0 0 1 0;
    }

    #watch-modal-error {
        color: $error;
        height: auto;
        padding: 0 0 1 0;
    }

    .watch-field-label {
        padding: 0 0 0 0;
        height: 1;
    }

    #watch-label-input,
    #watch-query-input,
    #watch-company-input,
    #watch-location-input {
        margin: 0 0 1 0;
    }

    #watch-seniority-select {
        margin: 0 0 1 0;
    }

    #watch-buttons {
        padding: 1 0 0 0;
        align: center middle;
    }

    #watch-create-btn {
        margin: 0 1 0 0;
    }
    """

    def __init__(self, *, client) -> None:
        super().__init__()
        self.client = client

    def compose(self) -> ComposeResult:
        with Container(id="watch-modal-container"):
            yield Static("[bold]Create Watch[/bold]", id="watch-modal-title")
            yield Label("Label (required)", classes="watch-field-label")
            yield Input(
                placeholder="e.g. ML Roles in SF",
                id="watch-label-input",
            )
            yield Label("Query (required)", classes="watch-field-label")
            yield Input(
                placeholder="e.g. backend engineer with Rust and distributed systems",
                id="watch-query-input",
            )
            yield Label("Seniority", classes="watch-field-label")
            yield Select(
                SENIORITY_OPTIONS,
                id="watch-seniority-select",
                allow_blank=False,
                value="",
            )
            yield Label("Company", classes="watch-field-label")
            yield Input(
                placeholder="e.g. Stripe, Anthropic",
                id="watch-company-input",
            )
            yield Label("Location", classes="watch-field-label")
            yield Input(
                placeholder="e.g. San Francisco, CA",
                id="watch-location-input",
            )
            yield Static("", id="watch-modal-error")
            with Horizontal(id="watch-buttons"):
                yield Button("Create", id="watch-create-btn", variant="primary")
                yield Button("Cancel", id="watch-cancel-btn")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "watch-cancel-btn":
            self.dismiss(False)
        elif event.button.id == "watch-create-btn":
            self._submit()

    def _submit(self) -> None:
        """Validate form and dispatch the create worker."""
        error_widget = self.query_one("#watch-modal-error", Static)
        error_widget.update("")

        # Validate label
        label = self.query_one("#watch-label-input", Input).value.strip()
        if not label:
            error_widget.update("A label is required.")
            return
        if len(label) > 100:
            error_widget.update("Label must be 100 characters or fewer.")
            return

        # Validate query
        query = self.query_one("#watch-query-input", Input).value.strip()
        if not query:
            error_widget.update("A query is required.")
            return
        if len(query) < 10:
            error_widget.update("Query must be at least 10 characters.")
            return
        if len(query) > 500:
            error_widget.update("Query must be 500 characters or fewer.")
            return

        # Get seniority
        seniority = self.query_one("#watch-seniority-select", Select).value

        # Get company
        company_raw = self.query_one("#watch-company-input", Input).value.strip()
        company_slug = company_raw.lower().replace(" ", "-") if company_raw else ""

        # Get location
        location = self.query_one("#watch-location-input", Input).value.strip()

        self._do_create(label, query, seniority, company_slug, location)

    @work(thread=True, exit_on_error=False)
    def _do_create(
        self,
        label: str,
        query: str,
        seniority: str,
        company_slug: str,
        location: str,
    ) -> None:
        try:
            self.client.create_watch(
                label=label,
                query=query,
                seniority=seniority,
                company_slug=company_slug,
                location=location,
            )
        except httpx.HTTPStatusError as exc:
            if exc.response.status_code == 409:
                msg = "Watch limit reached (5)."
            else:
                msg = f"Failed to create watch (HTTP {exc.response.status_code})."
            self.app.call_from_thread(
                self.query_one("#watch-modal-error", Static).update, msg
            )
            return
        except Exception:
            self.app.call_from_thread(
                self.query_one("#watch-modal-error", Static).update,
                "Something went wrong. Please try again.",
            )
            return
        self.app.call_from_thread(self.dismiss, True)

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