"""Shared widgets for menu-style screens."""

from __future__ import annotations

from rich.text import Text
from textual.app import ComposeResult
from textual.screen import ModalScreen
from textual.reactive import reactive
from textual.widgets import Static, Button, Input
from textual.containers import Vertical


class MenuOption(Static):
    """A selectable menu row with a label and a current value."""

    highlighted = reactive(False)

    DEFAULT_CSS = """
    MenuOption {
        width: 100%;
        height: 3;
        padding: 1 1;
    }
    MenuOption.highlighted {
        background: $primary-background;
    }
    MenuOption.hidden, .hidden {
        display: none;
    }
    """

    def __init__(self, label: str, option_id: str) -> None:
        super().__init__(id=option_id)
        self.label = label

    def set_value(self, value_renderable: str | Text) -> None:
        if isinstance(value_renderable, str):
            text = Text()
            text.append(f" {self.label:<14} ", style="bold" if self.highlighted else "")
            text.append(value_renderable)
        else:
            text = Text()
            text.append(f" {self.label:<14} ", style="bold" if self.highlighted else "")
            text.append_text(value_renderable)
        self.update(text)

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


class TokenInputModal(ModalScreen[str]):
    """Modal for entering Lichess API token."""

    DEFAULT_CSS = """
    TokenInputModal {
        align: center middle;
    }
    #token-container {
        width: 56;
        height: auto;
        border: heavy $primary;
        padding: 1 2;
        background: $surface;
    }
    #token-hint {
        color: $text-muted;
        margin: 0 0 1 0;
    }
    #token-input {
        margin: 0 0 1 0;
    }
    """

    BINDINGS = [("escape", "cancel", "Cancel")]

    def compose(self) -> ComposeResult:
        with Vertical(id="token-container"):
            yield Static("Enter your Lichess API token:")
            yield Static(
                "Get one at lichess.org/account/oauth/token",
                id="token-hint",
            )
            yield Input(placeholder="lip_...", password=True, id="token-input")
            yield Button("Save", id="btn-token-save", variant="primary")
            yield Button("Cancel", id="btn-token-cancel")

    def on_mount(self) -> None:
        self.query_one("#token-input", Input).focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-token-save":
            token = self.query_one("#token-input", Input).value.strip()
            self.dismiss(token)
        else:
            self.dismiss("")

    def on_input_submitted(self, event: Input.Submitted) -> None:
        token = event.value.strip()
        self.dismiss(token)

    def action_cancel(self) -> None:
        self.dismiss("")
