"""
Configuration modal window for the hosts TUI application.

This module provides a floating configuration window for managing application settings.
"""

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

from ..core.config import Config
from .styles import CONFIG_MODAL_CSS


class ConfigModal(ModalScreen):
    """
    Modal screen for application configuration.

    Provides a floating window with configuration options.
    """

    CSS = CONFIG_MODAL_CSS

    BINDINGS = [
        Binding("escape", "cancel", "Cancel"),
        Binding("enter", "save", "Save"),
    ]

    def __init__(self, config: Config):
        super().__init__()
        self.config = config

    def compose(self) -> ComposeResult:
        """Create the configuration modal layout."""
        with Vertical(classes="config-container"):
            yield Static("Configuration", classes="config-title")

            with Vertical(classes="config-section"):
                yield Label("Display Options:")
                yield Checkbox(
                    "Show default system entries (localhost, broadcasthost)",
                    value=self.config.should_show_default_entries(),
                    id="show-defaults-checkbox",
                    classes="config-option",
                )

            with Horizontal(classes="button-row"):
                yield Button(
                    "Save", variant="primary", id="save-button", classes="config-button"
                )
                yield Button(
                    "Cancel (ESC)",
                    variant="default",
                    id="cancel-button",
                    classes="default-button",
                )

    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 == "cancel-button":
            self.action_cancel()

    def action_save(self) -> None:
        """Save configuration and close modal."""
        # Get checkbox state
        checkbox = self.query_one("#show-defaults-checkbox", Checkbox)
        self.config.set("show_default_entries", checkbox.value)
        self.config.save()

        # Close modal and signal that config was changed
        self.dismiss(True)

    def action_cancel(self) -> None:
        """Cancel configuration changes and close modal."""
        self.dismiss(False)
