"""Opening selection screen — flat list of available openings."""

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 Vertical

from chess_cli.openings import get_all_openings
from chess_cli.openings.models import Opening


class OpeningItem(Static):
    """A selectable opening in the list."""

    highlighted = reactive(False)

    DEFAULT_CSS = """
    OpeningItem {
        width: 100%;
        height: 3;
        padding: 0 2;
        margin-bottom: 1;
        content-align: left middle;
    }
    OpeningItem.white-opening {
        background: rgb(55,50,45);
    }
    OpeningItem.black-opening {
        background: rgb(40,45,55);
    }
    OpeningItem.highlighted {
        border-left: thick white;
    }
    """

    def __init__(self, opening: Opening) -> None:
        super().__init__()
        self.opening = opening
        if opening.color == chess.WHITE:
            self.add_class("white-opening")
        else:
            self.add_class("black-opening")

    def render(self) -> Text:
        text = Text()
        icon = "\u265a" if self.opening.color == chess.WHITE else "\u2654"
        color_label = "White" if self.opening.color == chess.WHITE else "Black"
        style = "bold" if self.highlighted else ""
        text.append(f" {icon} ", style=style)
        text.append(self.opening.name, style=style)
        text.append(f"  ({color_label})", style="dim")
        text.append(f"\n   {self.opening.description}", style="dim")
        return text

    def watch_highlighted(self, value: bool) -> None:
        self.set_class(value, "highlighted")


class OpeningSelectScreen(Screen):
    """Screen listing all available openings."""

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

#opening-container {
    width: 64;
    height: auto;
    max-height: 80%;
    border: heavy $primary;
    padding: 2 3;
    background: $surface;
}

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

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

#opening-hint {
    width: 100%;
    height: 1;
    margin-top: 2;
    color: $text-muted;
    padding: 0 1;
    text-align: center;
}
"""

    BINDINGS = [
        ("up", "focus_prev", "Up"),
        ("down", "focus_next", "Down"),
        ("enter", "select", "Select"),
        ("escape", "back", "Back"),
        ("q", "back", "Back"),
    ]

    focus_index: reactive[int] = reactive(0)

    def __init__(self) -> None:
        super().__init__()
        self._openings = get_all_openings()

    def compose(self) -> ComposeResult:
        yield Header(show_clock=False)
        with Vertical(id="opening-container"):
            yield Static("♞  L E A R N   O P E N I N G S", id="opening-title")
            yield Static("── Select an Opening ──────────────────", classes="section-header")
            for opening in self._openings:
                yield OpeningItem(opening)
            yield Static("↑↓ navigate · Enter select · q back", id="opening-hint")
        yield Footer()

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

    def _update_highlight(self) -> None:
        items = self.query(OpeningItem)
        for i, item in enumerate(items):
            item.highlighted = i == self.focus_index

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

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

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

    def action_select(self) -> None:
        if self._openings:
            opening = self._openings[self.focus_index]
            from chess_cli.tui.screens.opening_mode import OpeningModeScreen
            self.app.push_screen(OpeningModeScreen(opening))

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