"""People 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 PersonTableRow:
    """Read model consumed by the people table component."""

    id: UUID
    full_name: str
    display_name: str
    maiden_name: str
    birth_date: str


def _serialize_rows(rows: Sequence[PersonTableRow]) -> list[dict[str, Any]]:
    return [
        {
            "id": str(row.id),
            "full_name": row.full_name,
            "display_name": row.display_name or "Not set",
            "maiden_name": row.maiden_name or "N/A",
            "birth_date": row.birth_date or "Unknown",
        }
        for row in rows
    ]


def render_people_table(rows: Sequence[PersonTableRow]) -> None:
    """Render people table with search filtering and custom typography."""
    if not rows:
        with archival_card(extra_classes="p-8 text-center"):
            render_empty_state("No person records found in repository.")
        return

    table = build_table(
        rows=_serialize_rows(rows),
        columns=[
            {
                "name": "full_name",
                "label": "Full Name",
                "field": "full_name",
                "sortable": True,
                "classes": "font-serif font-semibold",
            },
            {
                "name": "display_name",
                "label": "Display Name",
                "field": "display_name",
                "sortable": True,
            },
            {
                "name": "maiden_name",
                "label": "Maiden Name",
                "field": "maiden_name",
                "sortable": True,
            },
            {
                "name": "birth_date",
                "label": "Birth Date",
                "field": "birth_date",
                "sortable": True,
                "classes": "font-mono text-xs",
            },
        ],
        default_sort_by="full_name",
        search_placeholder="Search people by name or birth date...",
        on_row_click_id=lambda person_id: ui.navigate.to(f"/people/{person_id}"),
    )

    # Custom column template adding an archival entity icon next to person's name
    table.add_slot(
        "body-cell-full_name",
        r"""
        <q-td :props="props">
            <div class="row items-center q-gutter-x-xs">
                <q-icon name="person" size="xs" color="primary" />
                <span class="font-serif font-semibold">{{ props.value }}</span>
            </div>
        </q-td>
        """,
    )