"""Welcome screen — landing page with Start, Choose Lesson, and Quit."""

from __future__ import annotations

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

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


class WelcomeScreen(Screen[None]):
    """Landing screen shown when the TUI launches."""

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

    def compose(self) -> ComposeResult:
        yield Header()
        with Center():
            with Vertical(id="welcome-container"):
                yield Static(
                    "[bold cyan]Welcome to ONA Onboarding[/bold cyan]",
                    id="welcome-title",
                )
                yield Static(
                    "Learn to set up and configure ONA developer environments\n"
                    "through hands-on, interactive tutorials.",
                    id="welcome-subtitle",
                )
                yield Static(
                    "[bold]Before You Start:[/bold]\n\n"
                    "✓ GitLab account with access to gitlab.example.com\n"
                    "✓ A GitLab repository to practice with (existing or new)\n"
                    "✓ Repository cloned locally (recommended)\n\n"
                    "[bold]The Workflow:[/bold]\n"
                    "1. Learn concepts in these TUI lessons\n"
                    "2. Scaffold configuration files (button at bottom of each lesson)\n"
                    "3. Copy files from `./cde-onboard-practice/` to your repository\n"
                    "4. Commit and push to GitLab\n"
                    "5. Create/rebuild ONA environment to test\n\n"
                    "[dim]Tip: Run this CLI from your repository root "
                    "for easier file copying.[/dim]",
                    id="welcome-prerequisites",
                )
                yield Static(
                    "[dim]Scaffolded files are created under "
                    "`./cde-onboard-practice/lesson-XX-<slug>/` in the current directory.[/dim]",
                    id="welcome-practice-note",
                )
                completed = self.progress.data.total_completed
                if completed > 0:
                    yield Label(
                        f"[dim]Progress: {completed}/{TOTAL_LESSONS} lessons completed[/dim]",
                        id="welcome-progress",
                    )
                    next_lesson = self._next_incomplete_lesson()
                    if next_lesson is not None:
                        yield Button(
                            f"Resume Lesson {next_lesson}",
                            id="btn-resume",
                            variant="primary",
                        )
                yield Button("Start from Beginning", id="btn-start", variant="default")
                yield Button("Choose a Lesson", id="btn-choose", variant="default")
                yield Button("Quit", id="btn-quit", variant="error")
        yield Footer()

    def _next_incomplete_lesson(self) -> int | None:
        """Find the number of the first incomplete lesson."""
        for cls in get_all_lessons():
            meta = cls.meta()
            if not self.progress.is_completed(meta.id):
                return meta.number
        return None

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-resume":
            from cde_onboard.screens.lesson import LessonScreen

            next_lesson = self._next_incomplete_lesson()
            if next_lesson is not None:
                self.app.push_screen(LessonScreen(next_lesson, self.progress))
        elif event.button.id == "btn-start":
            from cde_onboard.screens.lesson import LessonScreen

            self.app.push_screen(LessonScreen(0, self.progress))
        elif event.button.id == "btn-choose":
            from cde_onboard.screens.lesson_menu import LessonMenuScreen

            self.app.push_screen(LessonMenuScreen(self.progress))
        elif event.button.id == "btn-quit":
            self.app.exit()
