"""Settings screen widget for TUI configuration."""

from __future__ import annotations

import importlib
from typing import Any

__all__ = ["SettingsScreen"]


def _load_static_base() -> type[Any]:
    """Load the Textual Static widget base class."""
    try:
        return importlib.import_module("textual.widgets").Static
    except Exception:  # pragma: no cover

        class _FallbackStatic:
            def __init__(self, *args: object, **kwargs: object) -> None:
                self._text = ""

            def update(self, text: str) -> None:
                self._text = text

        return _FallbackStatic


_StaticBase = _load_static_base()


def _render_settings_screen(
    selected_index: int,
    theme: str,
    default_actor: str,
    safety_level: str,
) -> str:
    """Render the settings screen content."""
    settings = [
        ("Theme", theme),
        ("Default Actor", default_actor),
        ("Safety Level", safety_level),
    ]

    lines = ["Settings", ""]
    for i, (name, value) in enumerate(settings):
        prefix = "❯ " if i == selected_index else "  "  # noqa: RUF001
        lines.append(f"{prefix}{name}: {value}")

    lines.extend(
        [
            "",
            "Navigation: j/k or ↑/↓ to move",
            "Edit: enter to modify selected setting",
            "Save: s to save changes",
            "Cancel: esc to discard changes",
        ]
    )

    return "\n".join(lines)


class SettingsScreen(_StaticBase):
    """TUI widget for displaying and editing application settings.

    Allows users to configure:
    - Theme (color scheme)
    - Default actor
    - Safety level
    - Other TUI preferences

    Keyboard bindings:
    - ``j`` / ``k`` or ``↑`` / ``↓``: navigate settings
    - ``enter``: edit selected setting
    - ``s``: save changes
    - ``escape``: discard changes and close
    """

    def __init__(self, *args: object, **kwargs: object) -> None:
        """Initialize the SettingsScreen."""
        super().__init__(*args, **kwargs)
        self._selected_index: int = 0
        self._theme: str = "dracula"
        self._default_actor: str = "default"
        self._safety_level: str = "medium"
        self._text: str = ""
        self._visible: bool = False
        self._refresh()

    @property
    def visible(self) -> bool:
        """Return whether the settings screen is currently visible."""
        return self._visible

    @property
    def selected_index(self) -> int:
        """Return the index of the currently selected setting."""
        return self._selected_index

    @property
    def theme(self) -> str:
        """Return the current theme setting."""
        return self._theme

    @property
    def default_actor(self) -> str:
        """Return the current default actor setting."""
        return self._default_actor

    @property
    def safety_level(self) -> str:
        """Return the current safety level setting."""
        return self._safety_level

    def show(self) -> None:
        """Show the settings screen."""
        self._visible = True
        self._refresh()

    def hide(self) -> None:
        """Hide the settings screen."""
        self._visible = False
        self._text = ""
        self.update("")

    def navigate_next(self) -> None:
        """Move selection to the next setting (``j`` or ``↓`` key)."""
        self._selected_index = (self._selected_index + 1) % 3
        self._refresh()

    def navigate_prev(self) -> None:
        """Move selection to the previous setting (``k`` or ``↑`` key)."""
        self._selected_index = (self._selected_index - 1) % 3
        self._refresh()

    def set_theme(self, theme: str) -> None:
        """Set the theme setting."""
        self._theme = theme
        self._refresh()

    def set_default_actor(self, actor: str) -> None:
        """Set the default actor setting."""
        self._default_actor = actor
        self._refresh()

    def set_safety_level(self, level: str) -> None:
        """Set the safety level setting."""
        self._safety_level = level
        self._refresh()

    def get_settings(self) -> dict[str, str]:
        """Return the current settings as a dictionary."""
        return {
            "theme": self._theme,
            "default_actor": self._default_actor,
            "safety_level": self._safety_level,
        }

    def _refresh(self) -> None:
        """Re-render the screen content."""
        if not self._visible:
            self._text = ""
            self.update("")
            return

        self._text = _render_settings_screen(
            self._selected_index,
            self._theme,
            self._default_actor,
            self._safety_level,
        )
        self.update(self._text)
