"""Sources table rendering helpers."""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
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 transcription.ui.components.table.common import build_table


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

    id: UUID
    page_number: int
    upload_name: str
    filename: str
    document_id: UUID
    document_name: str | None = None
    job_source_status: str | None = None
    job_source_error_detail: str | None = None


def _serialize_rows(rows: Sequence[SourceTableRow]) -> list[dict[str, Any]]:
    return [
        {
            "id": str(row.id),
            "page_number": row.page_number,
            "upload_name": row.upload_name,
            "filename": row.filename,
            "document_id": str(row.document_id),
            "document_name": row.document_name or "-",
            "job_source_status": row.job_source_status or "-",
            "job_source_error_detail": row.job_source_error_detail or "-",
        }
        for row in rows
    ]


def render_sources_table(rows: Sequence[SourceTableRow]) -> None:
    """Render sources table and open detail page when clicking a row."""
    if not rows:
        with archival_card(extra_classes="p-8 text-center"):
            render_empty_state("No source file records found in repository.")
        return

    table = build_table(
        rows=_serialize_rows(rows),
        columns=[
            {
                "name": "document_name",
                "label": "Document Name",
                "field": "document_name",
                "sortable": True,
                "classes": "font-serif",
            },
            {
                "name": "page_number",
                "label": "Page Number",
                "field": "page_number",
                "sortable": True,
            },
            {
                "name": "upload_name",
                "label": "Upload Title",
                "field": "upload_name",
                "sortable": True,
                "classes": "font-serif",
            },
            {
                "name": "filename",
                "label": "Stored Filename",
                "field": "filename",
                "sortable": True,
                "classes": "font-mono",
            },
            {
                "name": "job_source_status",
                "label": "Status",
                "field": "job_source_status",
                "sortable": True,
                "classes": "font-mono",
            },
            {
                "name": "job_source_error_detail",
                "label": "Error Detail",
                "field": "job_source_error_detail",
                "sortable": False,
                "classes": "font-mono text-xs truncate max-w-xs vibe-text-muted",
            },
        ],
        default_sort_by="page_number",
        on_row_click_id=lambda source_id: ui.navigate.to(f"/sources/{source_id}"),
    )

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