from __future__ import annotations

from textual import on
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.events import Key
from textual.screen import ModalScreen
from textual.widgets import Label, ListItem, ListView, Static

from termchat.themes import THEMES


class ThemeItem(ListItem):
    def __init__(self, theme_name: str, is_dark: bool, primary: str, secondary: str, accent: str, error: str, bg: str) -> None:
        super().__init__()
        self.theme_name = theme_name
        self._is_dark = is_dark
        self._primary = primary
        self._secondary = secondary
        self._accent = accent
        self._error = error
        self._bg = bg

    def compose(self) -> ComposeResult:
        dots = (
            f"[{self._primary}]\u2588\u2588[/]"
            f"[{self._secondary}]\u2588\u2588[/]"
            f"[{self._accent}]\u2588\u2588[/]"
            f"[{self._error}]\u2588\u2588[/]"
            f"[{self._bg}]\u2588\u2588[/]"
        )
        tag = " [dim]light[/]" if not self._is_dark else ""
        yield Static(f"{self.theme_name}{tag}  {dots}", classes="theme-preview")


class ThemeScreen(ModalScreen[None]):

    def __init__(self) -> None:
        super().__init__()
        self._original_theme: str | None = None

    def compose(self) -> ComposeResult:
        with Vertical(id="theme-modal"):
            yield Label("THEME", id="modal-title")
            yield ListView(id="theme-list")
            yield Static("[dim]↑↓ preview  enter select  esc cancel[/]", id="theme-hint")

    async def on_mount(self) -> None:
        self._original_theme = self.app.theme
        lv = self.query_one("#theme-list", ListView)
        for t in THEMES:
            await lv.append(ThemeItem(
                t.name,
                t.dark,
                t.primary,
                t.secondary,
                t.accent,
                t.error,
                t.background,
            ))

    def on_key(self, event: Key) -> None:
        if event.key == "escape":
            event.stop()
            event.prevent_default()
            if self._original_theme:
                self.app.theme = self._original_theme
            self.dismiss(None)

    @on(ListView.Highlighted, "#theme-list")
    def on_highlighted(self, event: ListView.Highlighted) -> None:
        item = event.item
        if isinstance(item, ThemeItem):
            self.app.theme = item.theme_name

    @on(ListView.Selected, "#theme-list")
    def on_selected(self, event: ListView.Selected) -> None:
        item = event.item
        if isinstance(item, ThemeItem):
            self.app.theme = item.theme_name
            from termchat.config import CONFIG_DIR
            theme_file = CONFIG_DIR / "theme"
            CONFIG_DIR.mkdir(parents=True, exist_ok=True)
            theme_file.write_text(item.theme_name)
            self.dismiss(None)
