"""Lesson screen — main teaching view with steps, code, and scaffold action."""

from __future__ import annotations

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

from cde_onboard.constants import PRACTICE_DIR_NAME, TOTAL_LESSONS
from cde_onboard.lessons import get_lesson
from cde_onboard.progress import ProgressManager
from cde_onboard.widgets.lesson_sidebar import LessonSidebar
from cde_onboard.widgets.step_view import StepView


class LessonScreen(Screen[None]):
    """Screen that teaches a single lesson through sequential steps."""

    def __init__(self, lesson_number: int, progress: ProgressManager) -> None:
        super().__init__()
        self.lesson_number = lesson_number
        self.progress = progress
        self._lesson = get_lesson(lesson_number)
        self._current_step = 0

    def compose(self) -> ComposeResult:
        meta = self._lesson.meta()
        steps = self._lesson.steps()

        yield Header()
        with Horizontal(id="lesson-layout"):
            yield LessonSidebar(self.progress, active_lesson=self.lesson_number)
            with Vertical(id="lesson-content"):
                yield Static(
                    f"[bold cyan]Lesson {meta.number}: {meta.title}[/bold cyan]\n"
                    f"[dim]{meta.overview}[/dim]",
                    id="lesson-header",
                )
                with VerticalScroll(id="steps-container"):
                    for i, step in enumerate(steps):
                        yield StepView(step, step_number=i + 1)
                with Horizontal(id="lesson-actions"):
                    yield Button("← Back", id="btn-back", variant="default")
                    if self._lesson.scaffold_files():
                        yield Button(
                            "Scaffold & Complete",
                            id="btn-scaffold",
                            variant="success",
                        )
                    else:
                        yield Button(
                            "Mark Complete",
                            id="btn-scaffold",
                            variant="success",
                        )
                    if self.lesson_number < TOTAL_LESSONS - 1:
                        yield Button(
                            "Next Lesson →",
                            id="btn-next",
                            variant="primary",
                        )
        yield Footer()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-back":
            self.app.pop_screen()
        elif event.button.id == "btn-scaffold":
            self._scaffold_and_complete()
        elif event.button.id == "btn-next":
            if not self.progress.is_completed(self._lesson.meta().id):
                self.notify(
                    "Tip: Complete this lesson first to save progress.",
                    title="Lesson Not Completed",
                    severity="warning",
                )
                return
            self.app.pop_screen()
            self.app.push_screen(
                LessonScreen(self.lesson_number + 1, self.progress)
            )

    def _scaffold_and_complete(self) -> None:
        """Scaffold files and mark the lesson as completed."""
        from cde_onboard.scaffolder import scaffold_lesson

        meta = self._lesson.meta()
        files = self._lesson.scaffold_files()

        try:
            created = scaffold_lesson(
                lesson_number=meta.number,
                lesson_slug=meta.id,
                files=files,
            )
        except (FileNotFoundError, OSError, ValueError) as exc:
            self.notify(
                f"Scaffolding failed: {exc}",
                title="Scaffold Failed",
                severity="error",
            )
            return

        self.progress.mark_completed(meta.id)

        # Refresh sidebar to reflect new completion status
        self._refresh_sidebar()

        # Show confirmation
        if created:
            file_list = "\n".join(f"  • {p}" for p in created)
            practice_hint = (
                f"\n\nFiles are in ./{PRACTICE_DIR_NAME}/"
                f"lesson-{meta.number:02d}-{meta.id}/. "
                "Copy them into your repo and commit."
            )
            self.notify(
                f"Created {len(created)} file(s):\n{file_list}{practice_hint}",
                title=f"Lesson {meta.number} Complete!",
                severity="information",
            )
        else:
            self.notify(
                "Lesson completed! (No files to scaffold for this lesson.)",
                title=f"Lesson {meta.number} Complete!",
                severity="information",
            )

        # Check if all lessons are done
        if self.progress.data.total_completed >= TOTAL_LESSONS:
            from cde_onboard.screens.completion import CompletionScreen

            self.app.push_screen(CompletionScreen(self.progress))

    def _refresh_sidebar(self) -> None:
        """Replace the sidebar widget to reflect updated progress."""
        old = self.query_one(LessonSidebar)
        new_sidebar = LessonSidebar(self.progress, active_lesson=self.lesson_number)
        old.remove()
        self.query_one("#lesson-layout").mount(new_sidebar, before=0)
