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

from __future__ import annotations

from uuid import UUID

from fastapi import Request
from nicegui import ui

from transcription.app_state import resolve_session_factory
from transcription.models import JobStatus
from transcription.services.jobs import JobService
from transcription.ui.components.app_shell import render_navigation_header
from transcription.ui.components.table.jobs import render_jobs_table

from ..components.document_panzoom import render_document_panzoom
from ..components.table.jobs import JobTableRow
from ..components.transcript import render_transcript_revision_row


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

    @ui.page("/jobs")
    async def jobs_page(request: Request) -> None:
        session_factory = resolve_session_factory(request.app.state)
        jobs_service = JobService(session_factory=session_factory)
        render_navigation_header(current_path="/jobs")

        @ui.refreshable
        async def render_table() -> None:
            jobs = [
                JobTableRow(
                    id=job.id,
                    status=job.status.value,
                    filename=job.filename,
                    retry_count=job.retry_count,
                    created_at=job.created_at.isoformat(),
                    updated_at=job.updated_at.isoformat(),
                )
                for job in await jobs_service.list_jobs()
            ]
            render_jobs_table(jobs)

        ui.button("Refresh", on_click=render_table.refresh, icon="refresh")
        await render_table()

    @ui.page("/jobs/{job_id}")
    async def job_detail_page(job_id: str, request: Request) -> None:
        session_factory = resolve_session_factory(request.app.state)
        jobs_service = JobService(session_factory=session_factory)
        render_navigation_header(current_path="/jobs")

        job = await jobs_service.read_job(job_id=UUID(job_id))

        with ui.splitter(value=30).classes("w-full h-[calc(100vh-64px)]") as splitter:
            with splitter.before, ui.column(align_items="stretch").classes("w-full h-full p-4 gap-3"):
                render_document_panzoom(document=job.document)
            with splitter.after, ui.column(align_items="stretch").classes("w-full h-full p-4 gap-3"):
                with ui.row():
                    ui.button(icon="arrow_back", on_click=ui.navigate.back)
                with ui.row().classes("w-full items-center justify-between"):
                    ui.label(f"{job.id}").classes("text-h6 text-weight-bold")
                    match job.status:
                        case JobStatus.TRANSCRIBED:
                            ui.chip(job.status.value.upper(), color="green", text_color="white").props("outline")
                        case _:
                            ui.label(f"{job.status.value}").classes("text-subtitle1 text-weight-medium")
                    for i, transcript in enumerate(job.transcripts):
                        render_transcript_revision_row(transcript=transcript, initially_expanded=(i == 0))
