"""Walkthrough screen — step through an opening move by move with explanations."""

from __future__ import annotations

import chess
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
from textual.containers import Horizontal, Vertical

from chess_cli.openings.models import Opening, flatten_main_line
from chess_cli.tui.widgets.board import BoardWidget
from chess_cli.tui.widgets.explanation import ExplanationWidget
from chess_cli.tui.widgets.move_list import MoveListWidget


class WalkthroughScreen(Screen):
    """Step through an opening with explanations."""

    DEFAULT_CSS = """
WalkthroughScreen {
    layout: vertical;
}

#wt-top-info {
    height: 1;
    margin: 1 1 0 1;
    padding-left: 2;
}

#board-area {
    height: 1fr;
    min-height: 14;
    margin: 1 1;
}

#board {
    width: 28;
    height: 10;
}

#explain-panel {
    width: 1fr;
    min-width: 26;
    height: 100%;
    margin-left: 2;
    padding: 0 1;
}

#step-counter {
    width: 100%;
    height: 1;
    text-align: center;
    color: $text-muted;
    margin-top: 1;
    margin-bottom: 1;
}

#move-list {
    width: 100%;
    height: auto;
    max-height: 8;
    overflow-y: auto;
    border: round $primary-background;
    margin-top: 1;
}

#wt-status {
    height: 1;
    margin: 1 1;
    padding-left: 1;
    color: $text-muted;
    text-align: center;
}
"""

    BINDINGS = [
        ("right", "step_forward", "Next"),
        ("left", "step_back", "Prev"),
        ("l", "step_forward", ""),
        ("h", "step_back", ""),
        ("home", "step_start", "Start"),
        ("end", "step_end", "End"),
        ("escape", "back", "Back"),
        ("q", "back", "Back"),
    ]

    step_index: reactive[int] = reactive(-1)  # -1 = starting position

    def __init__(self, opening: Opening) -> None:
        super().__init__()
        self.opening = opening
        self._moves = flatten_main_line(opening)
        self._board = chess.Board()

    def compose(self) -> ComposeResult:
        yield Header(show_clock=False)
        yield Static("", id="wt-top-info")
        with Horizontal(id="board-area"):
            yield BoardWidget(id="board")
            with Vertical(id="explain-panel"):
                yield Static("", id="step-counter")
                yield ExplanationWidget(id="explanation")
                yield MoveListWidget(id="move-list")
        yield Static("← → navigate · q back", id="wt-status")
        yield Footer()

    def on_mount(self) -> None:
        top_info = self.query_one("#wt-top-info", Static)
        color_icon = "\u265a" if self.opening.color == chess.WHITE else "\u2654"
        top_info.update(f"{color_icon} {self.opening.name} — Walkthrough")

        board_widget = self.query_one("#board", BoardWidget)
        board_widget.perspective = self.opening.color == chess.WHITE
        self._render_step()

    def _render_step(self) -> None:
        # Rebuild board up to step_index
        self._board.reset()
        for i in range(self.step_index + 1):
            san = self._moves[i][0]
            move = self._board.parse_san(san)
            self._board.push(move)

        # Update board widget
        board_widget = self.query_one("#board", BoardWidget)
        board_widget.board_fen = self._board.fen()

        # Highlight last move
        if self.step_index >= 0:
            san = self._moves[self.step_index][0]
            # Re-parse on a copy to get from/to squares
            temp = chess.Board()
            for i in range(self.step_index):
                temp.push(temp.parse_san(self._moves[i][0]))
            move = temp.parse_san(self._moves[self.step_index][0])
            board_widget.highlight_from = move.from_square
            board_widget.highlight_to = move.to_square
        else:
            board_widget.highlight_from = -1
            board_widget.highlight_to = -1

        # Update explanation
        explanation = self.query_one("#explanation", ExplanationWidget)
        if self.step_index >= 0:
            san, expl = self._moves[self.step_index]
            explanation.move_san = san
            explanation.explanation = expl
        else:
            explanation.move_san = ""
            explanation.explanation = "Press → to begin stepping through the opening."

        # Update step counter
        total = len(self._moves)
        current = self.step_index + 1
        counter = self.query_one("#step-counter", Static)
        if self.step_index < 0:
            counter.update("Starting position")
        else:
            counter.update(f"Move {current} of {total}")

        # Update move list
        san_history = [m[0] for m in self._moves[: self.step_index + 1]]
        self.query_one("#move-list", MoveListWidget).update_moves(san_history)

    def watch_step_index(self, _value: int) -> None:
        self._render_step()

    def action_step_forward(self) -> None:
        if self.step_index < len(self._moves) - 1:
            self.step_index += 1

    def action_step_back(self) -> None:
        if self.step_index >= 0:
            self.step_index -= 1

    def action_step_start(self) -> None:
        self.step_index = -1

    def action_step_end(self) -> None:
        self.step_index = len(self._moves) - 1

    def action_back(self) -> None:
        self.app.pop_screen()
