"""Home screen for the ALiCE TUI — banner and verb menu."""

from __future__ import annotations

import importlib
from typing import TYPE_CHECKING

from textual.containers import Grid, Horizontal
from textual.screen import Screen
from textual.widgets import Button, Collapsible, Footer

from alice_cli.tui.widgets.banner import BannerWidget
from alice_cli.tui.widgets.clock import TerminalClock
from alice_cli.tui.widgets.typewriter import Typewriter

if TYPE_CHECKING:
    from textual.app import ComposeResult

# Lazy-import callables: verb → (module_path, class_name)
_SCREEN_REGISTRY: dict[str, tuple[str, str]] = {
    "chat": ("alice_cli.tui.screens.chat", "ChatScreen"),
    "compose": ("alice_cli.tui.screens.compose", "ComposeScreen"),
    "compare": ("alice_cli.tui.screens.compare", "CompareScreen"),
    "diagnose": ("alice_cli.tui.screens.diagnose", "DiagnoseScreen"),
    "dialog": ("alice_cli.tui.screens.dialog", "DialogScreen"),
    "get-secret": ("alice_cli.tui.screens.get_secret", "GetSecretScreen"),
    "invoke": ("alice_cli.tui.screens.invoke", "InvokeScreen"),
    "recall": ("alice_cli.tui.screens.recall", "RecallScreen"),
    "status": ("alice_cli.tui.screens.status", "StatusScreen"),
    "teaparty": ("alice_cli.tui.screens.teaparty", "TeaPartyScreen"),
}

# Verbs that have dedicated TUI screens
_SCREEN_VERBS = set(_SCREEN_REGISTRY.keys())

# Grouped verb layout matching CLI help groups
_VERB_GROUPS: list[tuple[str, list[str]]] = [
    ("AI / Models", ["invoke", "chat", "dialog", "compare", "summarize", "batch", "teaparty"]),
    ("Sessions", ["recall", "appraise"]),
    ("Authentication", ["auth", "status", "config", "diagnose"]),
    ("Secrets & Infrastructure", ["get-secret", "list-secrets", "list-models", "list-aliases"]),
    ("AgentCore", ["compose"]),
]

# All verbs shown in the menu (17 items) — derived from groups
VERB_LIST: list[str] = [verb for _, verbs in _VERB_GROUPS for verb in verbs]


class HomeScreen(Screen[None]):
    """Landing screen with ASCII banner and verb menu."""

    DEFAULT_CSS = """
    HomeScreen #quick-actions {
        height: 3;
        align: center middle;
        padding: 0 4;
    }

    HomeScreen #quick-actions Button {
        margin: 0 1;
    }

    HomeScreen .verb-grid {
        grid-size: 3;
        grid-gutter: 1 2;
        padding: 0 4;
        height: auto;
    }

    HomeScreen .verb-grid Button {
        width: 100%;
        min-width: 18;
        content-align: center middle;
    }

    HomeScreen .has-screen {
        border: tall #FFB000;
    }

    HomeScreen .cli-only {
        border: tall #2A1F00;
        color: #805800;
    }
    """

    BINDINGS = [
        ("q", "quit", "Quit"),
    ]

    @property
    def _wordstar(self) -> bool:
        return getattr(self.app, "wordstar", False)

    def compose(self) -> ComposeResult:
        yield BannerWidget()
        if self._wordstar:
            from alice_cli.tui.widgets.wordstar_bar import WordStarBar

            yield WordStarBar()
            yield Typewriter(
                "WORDSTAR MODE — DAISY WHEEL READY — SELECT COMMAND",
                wordstar=True,
                speed=0.04,
                id="home-status",
            )
        else:
            yield Typewriter("TERMINAL READY — SELECT COMMAND", id="home-status")

        # Quick Actions row
        with Horizontal(id="quick-actions"):
            yield Button("chat", id="btn-chat", variant="primary")
            yield Button("invoke", id="btn-invoke", variant="primary")
            yield Button("compose", id="btn-compose", variant="primary")

        # Grouped sections
        for group_name, verbs in _VERB_GROUPS:
            with Collapsible(title=group_name), Grid(classes="verb-grid"):
                for verb in verbs:
                    css_class = "has-screen" if verb in _SCREEN_VERBS else "cli-only"
                    yield Button(verb, id=f"btn-{verb}", classes=css_class)

        yield TerminalClock()
        yield Footer()

    def key_j(self) -> None:
        """Move focus to the next focusable child (vim-style down).

        No-ops when a text input (Input / TextArea) is focused so
        ``j`` types normally.
        """
        from textual.widgets import Input, TextArea

        if isinstance(self.focused, Input | TextArea):
            return
        self.focus_next()

    def key_k(self) -> None:
        """Move focus to the previous focusable child (vim-style up).

        No-ops when a text input (Input / TextArea) is focused so
        ``k`` types normally.
        """
        from textual.widgets import Input, TextArea

        if isinstance(self.focused, Input | TextArea):
            return
        self.focus_previous()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle verb button presses via the screen registry."""
        verb = (event.button.id or "").removeprefix("btn-")
        entry = _SCREEN_REGISTRY.get(verb)
        if entry is not None:
            module_path, class_name = entry
            mod = importlib.import_module(module_path)
            screen_cls = getattr(mod, class_name)
            self.app.push_screen(screen_cls())
        else:
            self.notify(f"'{verb}' is CLI-only for now. Use: alice {verb}", severity="information")
