"""Tag management modal for adding/removing tags from content.

Provides a modal screen that allows users to manage tags on a content part,
with the ability to search for tags and toggle their selection.
"""

from typing import Any

from textual import on
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, Label, Static

from alloy_runtime_sdk.api_client.client import ApiClient

from cli.infrastructure.forms.tag_picker import TagPicker


class TagManagementModal(ModalScreen[list[str] | None]):
    """Modal for managing tags on a content part.

    Allows users to search for and select multiple tags. Returns the
    updated list of tag paths on save, or None if cancelled.

    Usage:
        def on_tags_saved(result: list[str] | None):
            if result is not None:
                # result is the list of tag paths to set
                pass

        self.push_screen(
            TagManagementModal(
                client=server_client,
                content_part_id="uuid-here",
                current_tags=[{"tag_path": "existing.tag", ...}],
            ),
            on_tags_saved
        )
    """

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

    def __init__(
        self,
        client: ApiClient,
        content_part_id: str,
        current_tags: list[dict[str, Any]],
        **kwargs: Any,
    ) -> None:
        """Initialize the tag management modal.

        Args:
            client: ApiClient instance for API calls
            content_part_id: ID of the content part being edited
            current_tags: Current tags on the content part
        """
        super().__init__(**kwargs)
        self._client = client
        self._content_part_id = content_part_id
        self._current_tags = current_tags

    def compose(self) -> ComposeResult:
        display_id = self._content_part_id

        with Vertical():
            yield Label("Manage Tags", classes="modal-title")
            yield Static(f"Content: {display_id}", classes="content-info")
            yield Static("Search and select tags:", classes="section-label")
            yield TagPicker(
                client=self._client,
                placeholder="Search for tags...",
                empty_message="No tags selected",
                id="tag-picker",
            )
            with Horizontal(classes="button-row"):
                yield Button("Save", id="save-btn", variant="success")
                yield Button("Cancel", id="cancel-btn", variant="default")

    def on_mount(self) -> None:
        """Pre-populate with current tags."""
        picker = self.query_one("#tag-picker", TagPicker)
        if self._current_tags:
            picker.set_initial_selection(self._current_tags)

    @on(Button.Pressed, "#save-btn")
    def on_save_pressed(self, event: Button.Pressed) -> None:
        """Save and dismiss with selected tags."""
        picker = self.query_one("#tag-picker", TagPicker)
        self.dismiss(picker.selected_tags)

    @on(Button.Pressed, "#cancel-btn")
    def on_cancel_pressed(self, event: Button.Pressed) -> None:
        """Cancel and dismiss with None."""
        self.dismiss(None)

    def action_cancel(self) -> None:
        """Cancel via escape key."""
        self.dismiss(None)
