"""Jobs table rendering helpers."""

from __future__ import annotations

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

from nicegui import ui

from transcription.ui.components.cards import archival_card
from transcription.ui.components.primitives import render_empty_state
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
    date_created: str
    date_updated: str


def _format_timestamp(value: str) -> str:
    """Return a friendly local 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.lower(),
            "filename": row.filename,
            "retry_count": row.retry_count,
            "date_created": _format_timestamp(row.date_created),
            "date_updated": _format_timestamp(row.date_updated),
            "created_sort": row.date_created,
            "updated_sort": row.date_updated,
        }
        for row in rows
    ]


def render_jobs_table(rows: Sequence[JobTableRow]) -> None:
    """Render jobs table with search filtering and custom status chips."""
    if not rows:
        with archival_card(extra_classes="p-8 text-center"):
            render_empty_state("No job records found in repository.")
        return

    table = build_table(
        rows=_serialize_rows(rows),
        columns=[
            {
                "name": "id",
                "label": "Job ID",
                "field": "id",
                "sortable": True,
                "classes": "font-mono text-xs",
            },
            {
                "name": "status",
                "label": "Status",
                "field": "status",
                "sortable": True,
                "classes": "font-mono",
            },
            {
                "name": "filename",
                "label": "Source Filename",
                "field": "filename",
                "sortable": True,
                "classes": "font-mono text-xs",
            },
            {
                "name": "retry_count",
                "label": "Retries",
                "field": "retry_count",
                "sortable": True,
            },
            {
                "name": "date_created",
                "label": "Created",
                "field": "created_sort",
                "sortable": True,
            },
            {
                "name": "date_updated",
                "label": "Updated",
                "field": "updated_sort",
                "sortable": True,
            },
        ],
        default_sort_by="created_sort",
        default_descending=True,
        search_placeholder="Search jobs by ID, filename, or status...",
        on_row_click_id=lambda job_id: ui.navigate.to(f"/jobs/{job_id}"),
    )

    # Render job execution status using themed Quasar chips
    table.add_slot(
        "body-cell-status",
        r"""
        <q-td :props="props">
            <q-chip 
                dense 
                square 
                size="sm"
                :color="
                    props.value === 'completed' || props.value === 'transcribed' ? 'positive' :
                    props.value === 'failed' ? 'negative' :
                    props.value === 'processing' ? 'secondary' :
                    props.value === 'queued' ? 'warning' : 'grey-6'
                "
                text-color="white"
            >
                {{ props.value.toUpperCase() }}
            </q-chip>
        </q-td>
        """,
    )