"""Confirmation modal for destructive actions."""

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, Static


class ConfirmModal(ModalScreen[bool]):
    """Modal for confirming destructive actions.

    Usage:
        def callback(confirmed: bool) -> None:
            if confirmed:
                # Perform action
                pass

        self.app.push_screen(
            ConfirmModal(
                title="Delete Agent",
                message="Delete agent 'my-agent'? This cannot be undone.",
            ),
            callback
        )
    """

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

    def __init__(
        self,
        title: str = "Confirm Action",
        message: str = "Are you sure?",
        **kwargs: Any,
    ) -> None:
        """Initialize the confirmation modal.

        Args:
            title: Modal title
            message: Confirmation message to display
            **kwargs: Additional keyword arguments for ModalScreen
        """
        super().__init__(**kwargs)
        self._title = title
        self._message = message

    def compose(self) -> ComposeResult:
        """Compose the modal layout."""
        with Vertical(id="confirm-modal"):
            yield Static(self._title, classes="modal-title")
            yield Static(self._message, id="confirm-message")

            with Horizontal(classes="button-row"):
                yield Button("Cancel", id="cancel-btn", variant="default")
                yield Button("Confirm", id="confirm-btn", variant="error")

    @on(Button.Pressed, "#confirm-btn")
    def on_confirm_pressed(self, event: Button.Pressed) -> None:
        """Confirm the action."""
        self.dismiss(True)

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

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