"""Lesson menu screen — picker showing all lessons with completion status."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, ListItem, ListView, Static

from cde_onboard.lessons import get_all_lessons
from cde_onboard.progress import ProgressManager


class LessonMenuItem(ListItem):
    """A single lesson entry in the menu list."""

    def __init__(self, number: int, title: str, description: str, completed: bool) -> None:
        super().__init__()
        self.lesson_number = number
        self._title = title
        self._description = description
        self._completed = completed

    def compose(self) -> ComposeResult:
        check = "[green]✓[/green]" if self._completed else "[dim]○[/dim]"
        yield Label(f"{check}  [bold]{self.lesson_number}. {self._title}[/bold]")
        yield Label(f"   [dim]{self._description}[/dim]")


class LessonMenuScreen(Screen[None]):
    """Screen showing all available lessons for selection."""

    def __init__(self, progress: ProgressManager) -> None:
        super().__init__()
        self.progress = progress

    def compose(self) -> ComposeResult:
        yield Header()
        with Vertical(id="menu-container"):
            yield Static(
                "[bold]Choose a Lesson[/bold]\n"
                "[dim]Select a lesson to begin or review.[/dim]",
                id="menu-title",
            )
            items: list[LessonMenuItem] = []
            for cls in get_all_lessons():
                meta = cls.meta()
                items.append(
                    LessonMenuItem(
                        number=meta.number,
                        title=meta.title,
                        description=meta.description,
                        completed=self.progress.is_completed(meta.id),
                    )
                )
            yield ListView(*items, id="lesson-list")
            yield Button("← Back", id="btn-back", variant="default")
        yield Footer()

    def on_list_view_selected(self, event: ListView.Selected) -> None:
        item = event.item
        if isinstance(item, LessonMenuItem):
            from cde_onboard.screens.lesson import LessonScreen

            self.app.push_screen(LessonScreen(item.lesson_number, self.progress))

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-back":
            self.app.pop_screen()
