from __future__ import annotations

from typing import TYPE_CHECKING, ClassVar

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

if TYPE_CHECKING:
    from textual.app import ComposeResult
    from textual.binding import BindingType


class AddCategoryModal(ModalScreen[str | None]):
    BINDINGS: ClassVar[list[BindingType]] = [
        ("down", "focus_next", "Next field"),
        ("up", "focus_previous", "Previous field"),
        ("escape", "cancel", "Cancel"),
    ]

    def compose(self) -> ComposeResult:
        with Vertical(id="modal-dialog"):
            yield Label("[#22c55e]Add Category[/]", id="modal-title")
            yield Label("Category name:", classes="modal-label")
            yield Input(placeholder="e.g. Groceries", id="category-name-input")
            with Horizontal(id="modal-buttons"):
                yield Button("Add", id="modal-confirm", variant="primary")
                yield Button("Cancel", id="modal-cancel", variant="default")

    def on_mount(self) -> None:
        self.query_one("#category-name-input", Input).focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "modal-confirm":
            self._submit()
        else:
            self.dismiss(None)

    def on_input_submitted(self, _event: Input.Submitted) -> None:
        self._submit()

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

    def _submit(self) -> None:
        name = self.query_one("#category-name-input", Input).value.strip()
        if name:
            self.dismiss(name)
        else:
            self.notify("Category name cannot be empty.", severity="error")
