"""Reusable jobs table rendering helpers."""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from uuid import UUID

from nicegui import ui


@dataclass(frozen=True)
class JobTableRow:
    """Read model consumed by the shared jobs table component."""

    id: UUID
    status: str
    created_at: str
    updated_at: str


def _serialize_rows(rows: Sequence[JobTableRow]) -> list[dict[str, str]]:
    """Convert typed rows into table-compatible dictionaries."""
    return [
        {
            "id": str(row.id),
            "status": row.status,
            "created_at": row.created_at,
            "updated_at": row.updated_at,
        }
        for row in rows
    ]


def render_jobs_table(rows: Sequence[JobTableRow]) -> None:
    """Render jobs table and per-row detail links."""
    if not rows:
        ui.label("No jobs yet.")
        return

    serialized_rows = _serialize_rows(rows)
    ui.table(
        columns=[
            {"name": "id", "label": "Job ID", "field": "id"},
            {"name": "status", "label": "Status", "field": "status"},
            {"name": "created_at", "label": "Created", "field": "created_at"},
            {"name": "updated_at", "label": "Updated", "field": "updated_at"},
        ],
        rows=serialized_rows,
        row_key="id",
    ).classes("w-full")

    with ui.column().classes("gap-1"):
        for row in serialized_rows:
            ui.link(f"Open {row['id']}", f"/jobs/{row['id']}")
