"""
Save confirmation modal for the hosts TUI application.

This module provides a modal dialog to confirm saving changes when exiting edit entry mode.
"""

from textual.app import ComposeResult
from textual.containers import Vertical, Horizontal
from textual.widgets import Static, Button, Label
from textual.screen import ModalScreen
from textual.binding import Binding

from .styles import SAVE_CONFIRMATION_MODAL_CSS


class SaveConfirmationModal(ModalScreen):
    """
    Modal screen for save confirmation when exiting edit entry mode.

    Provides a confirmation dialog asking whether to save or discard changes.
    """

    CSS = SAVE_CONFIRMATION_MODAL_CSS

    BINDINGS = [
        Binding("escape", "cancel", "Cancel"),
        Binding("enter", "save", "Save"),
        Binding("s", "save", "Save"),
        Binding("d", "discard", "Discard"),
    ]

    def compose(self) -> ComposeResult:
        """Create the save confirmation modal layout."""
        with Vertical(classes="save-confirmation-container"):
            yield Static("Save Changes?", classes="save-confirmation-title")
            yield Label(
                "You have made changes to this entry.\nDo you want to save or discard them?",
                classes="save-confirmation-message",
            )

            with Horizontal(classes="button-row"):
                yield Button(
                    "Save (S)",
                    variant="primary",
                    id="save-button",
                    classes="save-confirmation-button",
                )
                yield Button(
                    "Discard (D)",
                    variant="default",
                    id="discard-button",
                    classes="save-confirmation-button",
                )
                yield Button(
                    "Cancel (ESC)",
                    variant="default",
                    id="cancel-button",
                    classes="save-confirmation-button",
                )

    def on_mount(self) -> None:
        """Called when the modal is mounted. Set focus to the first button."""
        # Focus on the Save button by default
        save_button = self.query_one("#save-button", Button)
        save_button.focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "save-button":
            self.action_save()
        elif event.button.id == "discard-button":
            self.action_discard()
        elif event.button.id == "cancel-button":
            self.action_cancel()

    def action_save(self) -> None:
        """Save changes and close modal."""
        self.dismiss("save")

    def action_discard(self) -> None:
        """Discard changes and close modal."""
        self.dismiss("discard")

    def action_cancel(self) -> None:
        """Cancel operation and close modal."""
        self.dismiss("cancel")
