"""Documents 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 DocumentTableRow:
    """Read model consumed by the documents table component."""

    id: UUID
    name: str
    document_type: str
    archive_identifier: str
    created_at: str


def _serialize_rows(rows: Sequence[DocumentTableRow]) -> list[dict[str, Any]]:
    return [
        {
            "id": str(row.id),
            "name": row.name,
            "document_type": row.document_type or "Unspecified",
            "archive_identifier": row.archive_identifier or "N/A",
            "created_at": row.created_at,
        }
        for row in rows
    ]


def render_documents_table(rows: Sequence[DocumentTableRow]) -> None:
    """Render documents table with search filtering and custom type chips."""
    if not rows:
        with archival_card(extra_classes="p-8 text-center"):
            render_empty_state("No documents found in repository.")
        return

    table = build_table(
        rows=_serialize_rows(rows),
        columns=[
            {
                "name": "name",
                "label": "Document Title",
                "field": "name",
                "sortable": True,
                "classes": "font-serif font-semibold",
            },
            {
                "name": "document_type",
                "label": "Type",
                "field": "document_type",
                "sortable": True,
            },
            {
                "name": "archive_identifier",
                "label": "Archive Ref",
                "field": "archive_identifier",
                "sortable": True,
                "classes": "font-mono text-xs",
            },
            {
                "name": "created_at",
                "label": "Created",
                "field": "created_at",
                "sortable": True,
            },
        ],
        default_sort_by="name",
        search_placeholder="Search documents by title, type, or reference...",
        on_row_click_id=lambda doc_id: ui.navigate.to(f"/documents/{doc_id}"),
    )

    # Render document type using a subtle Quasar badge
    table.add_slot(
        "body-cell-document_type",
        r"""
        <q-td :props="props">
            <q-chip 
                dense 
                square 
                size="sm"
                color="primary"
                text-color="white"
            >
                {{ props.value }}
            </q-chip>
        </q-td>
        """,
    )