"""Jobs list and detail page registration."""

from __future__ import annotations

from uuid import UUID

from nicegui import ui
from sqlmodel import desc
from sqlmodel import select

from transcription.db import get_session
from transcription.models import Document
from transcription.models import Job
from transcription.models import Transcript
from transcription.ui.components.error_presenter import show_error
from transcription.ui.components.error_presenter import summarize_error
from transcription.ui.components.job_detail import render_job_detail
from transcription.ui.components.job_table import JobTableRow
from transcription.ui.components.job_table import render_jobs_table


async def fetch_jobs() -> list[JobTableRow]:
    """Return jobs for display in most-recent-first order."""
    async with get_session() as session:
        jobs = (await session.exec(select(Job).order_by(desc(Job.created_at)))).all()
        return [
            JobTableRow(
                id=job.id,
                status=job.status.value,
                created_at=job.created_at.isoformat(),
                updated_at=job.updated_at.isoformat(),
            )
            for job in jobs
        ]


async def fetch_job_detail(job_id: UUID) -> tuple[Job | None, Document | None, Transcript | None]:
    """Return job, document, and transcript for detail view."""
    async with get_session() as session:
        job = await session.get(Job, job_id)
        if job is None:
            return None, None, None
        document = await session.get(Document, job.document_id)
        transcript = (await session.exec(select(Transcript).where(Transcript.job_id == job.id))).first()
        return job, document, transcript


def register_page() -> None:
    """Register jobs list and detail routes."""

    @ui.page("/jobs")
    async def jobs_page() -> None:
        ui.label("Transcription Jobs")
        status = ui.label("Ready")

        @ui.refreshable
        async def render_table() -> None:
            jobs = await fetch_jobs()
            render_jobs_table(jobs)

        async def refresh() -> None:
            status.text = "Refreshing..."
            try:
                await render_table.refresh()
                status.text = "Refreshed"
            except Exception as exc:  # noqa: BLE001
                status.text = f"Refresh failed: {summarize_error(exc, operation='jobs.refresh')}"
                show_error(exc, title="Jobs refresh failed", operation="jobs.refresh")

        ui.button("Refresh", on_click=refresh)
        await render_table()
        ui.link("Back to upload", "/")

    @ui.page("/jobs/{job_id}")
    async def job_detail_page(job_id: str) -> None:
        ui.label("Job Detail")
        try:
            parsed_id = UUID(job_id)
        except ValueError:
            ui.label("Invalid job id")
            ui.link("Back to jobs", "/jobs")
            return

        job, document, transcript = await fetch_job_detail(parsed_id)
        if job is None:
            ui.label("Job not found")
            ui.link("Back to jobs", "/jobs")
            return

        render_job_detail(job=job, document=document, transcript=transcript)

        ui.link("Back to jobs", "/jobs")
