"""Confirmation modal screen.

A reusable modal dialog for confirming actions.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from textual.app import ComposeResult
    from textual.events import Key


class ConfirmModal(ModalScreen[bool]):
    """Modal confirmation dialog.

    A themed confirmation dialog that blocks the parent screen
    until the user confirms or cancels.

    Attributes:
        message: The message to display in the dialog.
        confirm_label: The label for the confirm button.
        cancel_label: The label for the cancel button.
    """

    def __init__(
        self,
        message: str,
        confirm_label: str = "Confirm",
        cancel_label: str = "Cancel",
    ) -> None:
        """Initialize the confirmation modal.

        Args:
            message: The message to display.
            confirm_label: Label for the confirm button.
            cancel_label: Label for the cancel button.
        """
        super().__init__()
        self.message = message
        self.confirm_label = confirm_label
        self.cancel_label = cancel_label

    def compose(self) -> ComposeResult:
        """Compose the modal layout."""
        with Container():
            yield Label(self.message, classes="dialog-content")
            with Horizontal(classes="dialog-actions"):
                yield Button(self.cancel_label, id="btn-cancel")
                yield Button(self.confirm_label, id="btn-confirm", variant="primary")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button press.

        Args:
            event: The button press event.
        """
        if event.button.id == "btn-confirm":
            self.dismiss(True)
        else:
            self.dismiss(False)

    def on_key(self, event: Key) -> None:
        """Handle key press.

        Args:
            event: The key event.
        """
        if event.key == "escape":
            self.dismiss(False)
        elif event.key in ("left", "right"):
            # Cycle focus between Cancel and Confirm buttons
            cancel_btn = self.query_one("#btn-cancel", Button)
            confirm_btn = self.query_one("#btn-confirm", Button)
            if cancel_btn.has_focus:
                confirm_btn.focus()
            else:
                cancel_btn.focus()


__all__ = ["ConfirmModal"]
