"""Reusable transcript UI components."""

from __future__ import annotations

from datetime import datetime
from typing import Any

from nicegui import ui

from transcription.models import Transcript


def render_transcript_revision_row(
    *,
    transcript: Transcript,
    initially_expanded: bool = False,
    classes: str = "w-full",
) -> Any:
    """Render one collapsible row for a single transcript revision."""
    status_label = "Failed" if transcript.error_detail else "Transcribed"
    header = f"Revision {transcript.revision} | {status_label}"
    caption = f"{transcript.provider} | {transcript.model} | {_format_created_at(transcript.created_at)}"

    expansion = ui.expansion(text=header, caption=caption, value=initially_expanded, group="group").classes(
        f"{classes} rounded-borders bg-blue-grey-10"
    )

    with expansion, ui.column().classes("w-full q-gutter-y-sm q-pa-sm"):
        _metadata_row(label="Provider", value=transcript.provider)
        _metadata_row(label="Model", value=transcript.model)
        _metadata_row(label="Created", value=_format_created_at(transcript.created_at))

        if transcript.text:
            with ui.card().classes("w-full q-pa-sm"):
                ui.markdown(transcript.text)

        if transcript.error_detail:
            with ui.card().classes("w-full bg-red-1 text-red-10 q-pa-sm"):
                ui.label("Failure detail").classes("text-caption text-uppercase")
                ui.label(transcript.error_detail).classes("text-body2")

    return expansion


def _format_created_at(value: datetime) -> str:
    """Return a compact UTC-like timestamp for row captions."""
    return value.strftime("%Y-%m-%d %H:%M:%S %Z")


def _metadata_row(*, label: str, value: str) -> None:
    with ui.row().classes("w-md items-start justify-between q-gutter-x-md"):
        ui.label(label).classes("text-caption text-grey-5 text-uppercase")
        ui.label(value).classes("text-body2 text-right text-grey-1 break-all")
