"""Project picker screen — landing page."""

from __future__ import annotations

from textual import on
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Center, Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Static
from textual.widgets.option_list import Option


class ProjectPickerScreen(Screen):
    BINDINGS = [
        Binding("n", "new_project", "New Project", show=True),
        Binding("q", "quit", "Quit", show=True),
    ]

    def compose(self) -> ComposeResult:
        with Center(id="picker-container"):
            with Vertical(id="picker-box"):
                yield Static("[bold]Select a Project[/bold]", id="picker-title")
                yield Static("", id="project-stats")
                yield Button("New Project", id="btn-new-project", variant="primary")
        yield Footer()

    def on_mount(self) -> None:
        self._refresh_projects()

    def _refresh_projects(self) -> None:
        from ..app import BanditoApp
        from ...retrieval import get_retrieval

        app: BanditoApp = self.app
        projects = app.store.list_projects()

        if not projects:
            self.query_one("#project-stats", Static).update(
                "[dim]No projects found. Press 'n' to create one.[/dim]"
            )
            return

        lines = []
        for p in projects:
            r = get_retrieval(p)
            traces = list(r.traces(tier="summary"))
            evals = r.evals()
            eval_count = len([e for e in evals.values() if e.get("human_score") is not None])
            ungraded = len(traces) - eval_count
            lines.append(f"  {p}  ·  {len(traces)} traces  ·  {ungraded} ungraded")

        self.query_one("#project-stats", Static).update("\n".join(lines))
        self._projects = projects

    @on(Button.Pressed, "#btn-new-project")
    def action_new_project(self) -> None:
        self.app.push_screen("NewProjectScreen")

    def on_key(self, event) -> None:
        if event.key == "enter":
            self._open_selected()
        elif event.key == "up":
            self._move_selection(-1)
        elif event.key == "down":
            self._move_selection(1)
        elif event.key == "n":
            self.action_new_project()
        else:
            return
        event.prevent_default()

    def _move_selection(self, delta: int) -> None:
        if not hasattr(self, "_projects") or not self._projects:
            return
        if not hasattr(self, "_selected"):
            self._selected = 0
        self._selected = (self._selected + delta) % len(self._projects)
        self._update_selection()

    def _update_selection(self) -> None:
        if not hasattr(self, "_projects") or not self._projects:
            return
        lines = []
        for i, p in enumerate(self._projects):
            r = get_retrieval(p)
            traces = list(r.traces(tier="summary"))
            evals = r.evals()
            eval_count = len([e for e in evals.values() if e.get("human_score") is not None])
            ungraded = len(traces) - eval_count
            prefix = "▸ " if i == self._selected else "  "
            lines.append(f"{prefix}{p}  ·  {len(traces)} traces  ·  {ungraded} ungraded")
        self.query_one("#project-stats", Static).update("\n".join(lines))

    def _open_selected(self) -> None:
        if not hasattr(self, "_projects") or not self._projects:
            return
        from ..app import BanditoApp

        app: BanditoApp = self.app
        app.project = self._projects[self._selected]
        self.app.push_screen("DashboardScreen")

    def action_quit(self) -> None:
        self.app.exit()