"""Quit confirmation dialog for Ghostty Settings TUI."""

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


class QuitDialog(ModalScreen[str]):
    """Modal dialog for confirming quit."""

    DEFAULT_CSS = """
    QuitDialog {
        align: center middle;
    }

    QuitDialog > Vertical {
        width: 40;
        height: auto;
        background: #282a36;
        border: double #bd93f9;
        padding: 1 2;
    }

    QuitDialog #dialog-title {
        width: 100%;
        height: 1;
        color: #ff79c6;
        text-style: bold;
        text-align: center;
        margin-bottom: 1;
    }

    QuitDialog #dialog-message {
        width: 100%;
        height: auto;
        color: #f8f8f2;
        text-align: center;
        margin-bottom: 1;
    }

    QuitDialog Button {
        width: 100%;
        margin: 0 0 1 0;
    }

    QuitDialog #btn-quit {
        background: #ff5555;
        color: #282a36;
    }

    QuitDialog #btn-save {
        background: #50fa7b;
        color: #282a36;
    }

    QuitDialog #btn-discard {
        background: #ffb86c;
        color: #282a36;
    }

    QuitDialog #btn-cancel {
        background: #6272a4;
        color: #f8f8f2;
    }

    QuitDialog Button:focus {
        text-style: bold reverse;
    }
    """

    BINDINGS = [
        Binding("escape", "cancel", "Cancel"),
        Binding("up", "move_up", "Up", show=False),
        Binding("down", "move_down", "Down", show=False),
        Binding("enter", "select_button", "Select", show=False),
    ]

    def __init__(self, has_unsaved: bool = False) -> None:
        super().__init__()
        self.has_unsaved = has_unsaved
        self._buttons: list[Button] = []
        self._focus_index = 0

    def compose(self) -> ComposeResult:
        with Vertical():
            if self.has_unsaved:
                yield Static("Unsaved Changes", id="dialog-title")
                yield Static(
                    "You have unsaved changes.\nWhat would you like to do?",
                    id="dialog-message"
                )
                yield Button("Save & Quit", id="btn-save")
                yield Button("Discard & Quit", id="btn-discard")
                yield Button("Cancel", id="btn-cancel")
            else:
                yield Static("Quit", id="dialog-title")
                yield Static(
                    "Are you sure you want to quit?",
                    id="dialog-message"
                )
                yield Button("Quit", id="btn-quit")
                yield Button("Cancel", id="btn-cancel")

    def on_mount(self) -> None:
        """Focus cancel button by default."""
        self._buttons = list(self.query(Button))
        # Focus last button (Cancel)
        self._focus_index = len(self._buttons) - 1
        if self._buttons:
            self._buttons[self._focus_index].focus()

    def action_move_up(self) -> None:
        """Move focus up."""
        if self._buttons:
            self._focus_index = (self._focus_index - 1) % len(self._buttons)
            self._buttons[self._focus_index].focus()

    def action_move_down(self) -> None:
        """Move focus down."""
        if self._buttons:
            self._focus_index = (self._focus_index + 1) % len(self._buttons)
            self._buttons[self._focus_index].focus()

    def action_select_button(self) -> None:
        """Press the focused button."""
        if self._buttons and 0 <= self._focus_index < len(self._buttons):
            self._buttons[self._focus_index].press()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-save":
            self.dismiss("save")
        elif event.button.id == "btn-discard" or event.button.id == "btn-quit":
            self.dismiss("discard")
        else:
            self.dismiss("cancel")

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