"""Jobs table rendering helpers."""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC
from datetime import datetime
from typing import Any
from uuid import UUID

from nicegui import ui

from .common import build_table


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

    id: UUID
    status: str
    filename: str
    retry_count: int
    created_at: str
    updated_at: str


def _format_timestamp(value: str) -> str:
    """Return a friendly UTC timestamp for table display."""
    try:
        parsed = datetime.fromisoformat(value)
    except ValueError:
        return value
    parsed = parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
    return parsed.astimezone().strftime("%b %d, %I:%M %p")


def _serialize_rows(rows: Sequence[JobTableRow]) -> list[dict[str, Any]]:
    return [
        {
            "id": str(row.id),
            "status": row.status,
            "filename": row.filename,
            "retry_count": row.retry_count,
            "created_at": _format_timestamp(row.created_at),
            "updated_at": _format_timestamp(row.updated_at),
            "created_sort": row.created_at,
            "updated_sort": row.updated_at,
        }
        for row in rows
    ]


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

    build_table(
        rows=_serialize_rows(rows),
        columns=[
            {"name": "id", "label": "Job ID", "field": "id", "sortable": True},
            {"name": "status", "label": "Status", "field": "status", "sortable": True},
            {"name": "filename", "label": "Filename", "field": "filename", "sortable": True},
            {"name": "retry_count", "label": "Retries", "field": "retry_count", "sortable": True},
            {"name": "created_at", "label": "Created", "field": "created_at", "sortable": True},
            {"name": "updated_at", "label": "Updated", "field": "updated_at", "sortable": True},
        ],
        default_sort_by="created_sort",
        default_descending=True,
        classes="app-table w-full",
        on_row_click_id=lambda job_id: ui.navigate.to(f"/jobs/{job_id}"),
    )
