"""Main menu screen — hub for navigating to settings, learning, and play."""

from __future__ import annotations

import shutil

from rich.text import Text
from textual.app import ComposeResult
from textual.screen import Screen
from textual.reactive import reactive
from textual.widgets import Static, Footer, Header, Button
from textual.containers import Vertical

from chess_cli.settings import load_settings

# ── Constants ────────────────────────────────────────────────────────

ASCII_TITLE = """\
      ♚  C H E S S   C L I
         ━━━━━━━━━━━━━━━━━"""

_FOCUSABLE = [
    "btn-engine",
    "btn-lichess",
    "btn-openings",
    "btn-play",
    "btn-analyze",
]


class MenuScreen(Screen):
    """Main menu — hub for navigating to subpages."""

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

#menu-container {
    width: 60;
    height: auto;
    max-height: 100%;
    border: heavy $primary;
    padding: 2 3;
    background: $surface;
    overflow-y: auto;
}

#menu-title {
    text-align: center;
    width: 100%;
    margin-bottom: 2;
    color: $text;
}

.section-header {
    width: 100%;
    height: 1;
    color: $text-muted;
    margin: 2 0 1 0;
    padding: 0 1;
}

#btn-engine {
    width: 100%;
    margin-top: 1;
}

#btn-lichess {
    width: 100%;
    margin-top: 1;
}

#btn-openings {
    width: 100%;
    margin-top: 1;
}

#btn-play {
    width: 100%;
    margin-top: 1;
}

#btn-analyze {
    width: 100%;
    margin-top: 1;
}

#status-bar {
    width: 100%;
    height: 1;
    margin-top: 2;
    color: $text-muted;
    padding: 0 1;
}
"""

    BINDINGS = [
        ("up", "focus_prev", "Up"),
        ("down", "focus_next", "Down"),
        ("enter", "select", "Select"),
        ("q", "quit", "Quit"),
    ]

    focus_index: reactive[int] = reactive(0)

    def compose(self) -> ComposeResult:
        yield Header(show_clock=False)
        with Vertical(id="menu-container"):
            yield Static(ASCII_TITLE, id="menu-title")
            yield Static("── Settings ───────────────────────────", classes="section-header")
            yield Button("⚙ Engine Settings", id="btn-engine")
            yield Button("🌐 Lichess Settings", id="btn-lichess")
            yield Static("── Play & Learn ───────────────────────", classes="section-header")
            yield Button("♞ Learn Openings", id="btn-openings", variant="success")
            yield Button("♚ Play Game", id="btn-play", variant="primary")
            yield Button("♛ Analyze PGN", id="btn-analyze")
            yield Static("", id="status-bar")
        yield Footer()

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    def on_mount(self) -> None:
        self._render_status_bar()
        self._update_highlight()

    # ------------------------------------------------------------------
    # Focus navigation
    # ------------------------------------------------------------------

    def _update_highlight(self) -> None:
        for btn_id in _FOCUSABLE:
            try:
                btn = self.query_one(f"#{btn_id}", Button)
                idx = _FOCUSABLE.index(btn_id)
                if idx == self.focus_index:
                    btn.focus()
                    btn.add_class("highlighted")
                else:
                    btn.remove_class("highlighted")
            except Exception:
                pass

    def watch_focus_index(self, value: int) -> None:
        self._update_highlight()

    def action_focus_prev(self) -> None:
        self.focus_index = (self.focus_index - 1) % len(_FOCUSABLE)

    def action_focus_next(self) -> None:
        self.focus_index = (self.focus_index + 1) % len(_FOCUSABLE)

    def action_select(self) -> None:
        if self.focus_index >= len(_FOCUSABLE):
            return
        current_id = _FOCUSABLE[self.focus_index]
        if current_id == "btn-engine":
            self._open_engine_settings()
        elif current_id == "btn-lichess":
            self._open_lichess_settings()
        elif current_id == "btn-openings":
            self._open_openings()
        elif current_id == "btn-play":
            self._open_play()
        elif current_id == "btn-analyze":
            self._action_analyze()

    # ------------------------------------------------------------------
    # Button handler
    # ------------------------------------------------------------------

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-engine":
            self._open_engine_settings()
        elif event.button.id == "btn-lichess":
            self._open_lichess_settings()
        elif event.button.id == "btn-openings":
            self._open_openings()
        elif event.button.id == "btn-play":
            self._open_play()
        elif event.button.id == "btn-analyze":
            self._action_analyze()

    # ------------------------------------------------------------------
    # Navigation
    # ------------------------------------------------------------------

    def _open_engine_settings(self) -> None:
        from chess_cli.tui.screens.engine_settings import EngineSettingsScreen
        self.app.push_screen(EngineSettingsScreen())

    def _open_lichess_settings(self) -> None:
        from chess_cli.tui.screens.lichess_settings import LichessSettingsScreen
        self.app.push_screen(LichessSettingsScreen())

    def _open_openings(self) -> None:
        from chess_cli.tui.screens.opening_select import OpeningSelectScreen
        self.app.push_screen(OpeningSelectScreen())

    def _open_play(self) -> None:
        from chess_cli.tui.screens.play import PlayScreen
        self.app.push_screen(PlayScreen())

    def _action_analyze(self) -> None:
        self.notify("Analysis from file not yet implemented")

    def action_quit(self) -> None:
        self.app.exit()

    # ------------------------------------------------------------------
    # Status bar
    # ------------------------------------------------------------------

    def _render_status_bar(self) -> None:
        text = Text()
        text.append("v0.1.0", style="dim")
        text.append("          ", style="dim")
        # Stockfish status
        sf_found = shutil.which("stockfish") is not None
        text.append("Stockfish: ", style="dim")
        text.append(
            "\u2713 detected" if sf_found else "\u2717 not found",
            style="green" if sf_found else "red",
        )
        text.append("   ", style="dim")
        # Lichess token status
        settings = load_settings()
        has_token = bool(settings.lichess_api_token)
        text.append("Lichess: ", style="dim")
        text.append(
            "\u2713 ready" if has_token else "\u2717 no token",
            style="green" if has_token else "red",
        )
        try:
            self.query_one("#status-bar", Static).update(text)
        except Exception:
            pass
