"""CodingListView — scrollable problem list for a coding category."""

from __future__ import annotations

import random
from dataclasses import dataclass

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.message import Message
from textual.widgets import DataTable, Static

from skilark_cli.tui.constants import DIFFICULTY_STARS


class CodingListView(Vertical):
    """Problem list for a single coding category."""

    @dataclass
    class ProblemSelected(Message):
        problem_id: str

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        self.category: str = ""
        self.problems: list[dict] = []

    def compose(self) -> ComposeResult:
        yield Static("", id="coding-list-header")
        yield DataTable(id="coding-problem-table")

    def on_mount(self) -> None:
        table = self.query_one("#coding-problem-table", DataTable)
        table.cursor_type = "row"
        table.add_columns("Difficulty", "Problem", "Status")

    def load(self, category: str, problems: list[dict]) -> None:
        """Populate the list with problems from API."""
        self.category = category
        self.problems = problems

        solved = sum(1 for p in problems if p.get("solved"))
        header = self.query_one("#coding-list-header", Static)
        header.update(f"[bold]{category}[/bold] ({solved}/{len(problems)} solved)")

        table = self.query_one("#coding-problem-table", DataTable)
        table.clear()
        for p in problems:
            stars = DIFFICULTY_STARS.get(p.get("difficulty", 1), "★☆☆")
            status = "✓ solved" if p.get("solved") else "unsolved"
            table.add_row(stars, p["title"], status)

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        idx = event.cursor_row
        if 0 <= idx < len(self.problems):
            self.post_message(self.ProblemSelected(self.problems[idx]["id"]))

    def get_random_unsolved_id(self) -> str | None:
        """Return a random unsolved problem ID, or None."""
        unsolved = [p for p in self.problems if not p.get("solved")]
        return random.choice(unsolved)["id"] if unsolved else None
