"""Reusable job detail rendering helpers."""

from __future__ import annotations

import logging
from collections.abc import Sequence

from nicegui import ui

from transcription.models import Document
from transcription.models import Job
from transcription.models import Transcript
from transcription.ui.components.document_panzoom import render_document_panzoom

logger = logging.getLogger(__name__)


def _status_chip_classes(status: str) -> str:
    if status == "queued":
        return "bg-blue-1 text-blue-10"
    if status == "processing":
        return "bg-amber-1 text-amber-10"
    if status == "transcribed":
        return "bg-green-1 text-green-10"
    if status == "failed":
        return "bg-red-1 text-red-10"
    return "bg-grey-2 text-grey-9"


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


def _render_document_section(document: Document) -> None:
    with ui.card().classes("w-full q-pa-md"):
        ui.label("Document").classes("text-subtitle1 text-weight-medium")
        ui.separator().classes("q-my-sm")
        with ui.column().classes("w-full q-gutter-y-xs"):
            _metadata_row("Filename", document.filename)
            _metadata_row("File path", document.file_path)

        ui.separator().classes("q-my-md")
        render_document_panzoom(document=document)


def _render_transcript_section(transcripts: Sequence[Transcript]) -> None:
    with ui.card().classes("w-full q-pa-md"):
        ui.label("Transcripts").classes("text-subtitle1 text-weight-medium")
        ui.separator().classes("q-my-sm")

        if not transcripts:
            ui.label("Transcript history is not available yet.").classes("text-body2 text-grey-3")
            return

        for transcript in transcripts:
            with ui.column().classes("w-full q-gutter-y-xs"):
                _metadata_row("Revision", str(transcript.revision))
                _metadata_row("Provider", transcript.provider)
                _metadata_row("Prompt", transcript.prompt_name)
                _metadata_row("Created", transcript.created_at.isoformat())

            if transcript.text:
                ui.separator().classes("q-my-sm")
                with ui.card().classes("w-fullq-pa-sm"):
                    ui.markdown(transcript.text).classes("text-grey-1")
            elif transcript.error_detail:
                ui.separator().classes("q-my-sm")
                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")

            ui.separator().classes("q-my-md bg-blue-grey-7")


def render_job_detail(*, job: Job, document: Document | None, transcripts: Sequence[Transcript]) -> None:
    """Render all sections for the job detail page."""
    logger.debug("Rendering job detail for job ID %s with %d transcripts", job.id, len(transcripts))
    status_text = job.status.value
    with ui.column().classes("w-full max-w-4xl q-gutter-md"):
        with ui.card().classes("w-full q-pa-lg"):
            with ui.row().classes("w-full items-center justify-between q-gutter-md"):
                with ui.column().classes("q-gutter-none"):
                    ui.label("Job overview").classes("text-h6 text-weight-bold")
                    ui.label(str(job.id)).classes("text-caption text-grey-5")
                status_chip_classes = (
                    "q-px-sm q-py-xs rounded-borders "
                    "text-weight-medium text-capitalize "
                    f"{_status_chip_classes(status_text)}"
                )
                ui.label(status_text).classes(status_chip_classes)

            ui.separator().classes("q-my-md bg-blue-grey-7")
            with ui.column().classes("w-full q-gutter-y-xs"):
                _metadata_row("Created", job.created_at.isoformat())
                _metadata_row("Updated", job.updated_at.isoformat())
                _metadata_row("Retries", str(job.retry_count))

        if document is not None:
            _render_document_section(document)

        _render_transcript_section(transcripts)
