"""Sources UI page module for VibeScribe."""

from __future__ import annotations

from typing import Optional
from uuid import UUID

from nicegui import ui

from transcription.services.transcription import TranscriptionNotFoundError
from transcription.services.transcription import TranscriptionService
from transcription.ui.components.app_shell import render_navigation_header
from transcription.ui.components.cards import archival_card
from transcription.ui.components.error_presenter import show_error
from transcription.ui.components.primitives import section_header_row
from transcription.ui.components.primitives import render_empty_state
from transcription.ui.theme import page_header

from ...db.session import SessionFactoryDep


async def sources_page(
    session_factory: SessionFactoryDep,
    document_id: Optional[str] = None,
    job_id: Optional[str] = None,
) -> None:
    """Render the master or context-filtered sources page."""
    sources_service = TranscriptionService(session_factory=session_factory)
    parsed_doc_id: Optional[UUID] = None
    parsed_job_id: Optional[UUID] = None

    if document_id:
        try:
            parsed_doc_id = UUID(document_id)
        except ValueError:
            pass

    if job_id:
        try:
            parsed_job_id = UUID(job_id)
        except ValueError:
            pass

    try:
        sources = await sources_service.list_sources_detail(document_id=parsed_doc_id, job_id=parsed_job_id)
    except Exception as exc:  # noqa: BLE001
        show_error(exc, title="Load failed", operation="sources.list")
        return

    header_title = "Source Asset Records"
    if parsed_doc_id:
        header_title = "Sources for Document"
    elif parsed_job_id:
        header_title = "Sources for Job"

    render_navigation_header(current_path="/sources")

    with ui.column().classes("w-full max-w-7xl mx-auto p-6 gap-6"):
        with section_header_row():
            page_header(header_title)

        if not sources:
            with archival_card(extra_classes="p-8 text-center"):
                render_empty_state("No source file records found in repository.")
            return

        columns = [
            {"name": "upload_name", "label": "Upload Name", "field": "upload_name", "align": "left", "sortable": True},
            {"name": "document_name", "label": "Document Context", "field": "document_name", "align": "left", "sortable": True},
            {"name": "page_number", "label": "Page #", "field": "page_number", "align": "center", "sortable": True},
            {"name": "status", "label": "Latest Status", "field": "status", "align": "center", "sortable": True},
            {"name": "revised", "label": "Human Revised", "field": "revised", "align": "center", "sortable": True},
            {"name": "actions", "label": "Actions", "field": "actions", "align": "right"},
        ]

        rows = [
            {
                "id": str(source.id),
                "upload_name": source.upload_name,
                "document_name": source.document_name or "Unlinked Document",
                "page_number": source.page_number,
                "status": source.latest_status.value if source.latest_status else "Unprocessed",
                "revised": "Yes" if source.revised_text else "No",
                "error_detail": source.latest_error_detail,
            }
            for source in sources
        ]

        with archival_card(extra_classes="p-0 overflow-hidden"):
            table = ui.table(columns=columns, rows=rows, row_key="id").classes("w-full ui-table")

            table.add_slot(
                "body-cell-actions",
                r"""
                <q-td :props="props">
                    <q-btn flat round dense icon="visibility" color="primary" @click="() => $parent.$emit('view_source', props.row.id)" />
                    <q-btn flat round dense icon="delete" color="negative" @click="() => $parent.$emit('delete_source', props.row.id)" />
                </q-td>
                """,
            )

            table.on("view_source", lambda e: ui.navigate.to(f"/sources/{e.args}"))
            table.on("delete_source", lambda e: ui.navigate.to(f"/sources/{e.args}/delete"))


async def source_detail_page(source_id: str, session_factory: SessionFactoryDep) -> None:
    """Render individual source detail preview and revision workspace."""
    _ = session_factory

    render_navigation_header(current_path="/sources")

    with ui.column().classes("w-full max-w-7xl mx-auto p-6 gap-6"):
        with archival_card(title=f"Source Record: {source_id}"):
            ui.label("Source Preview & Revision Workspace").classes("ui-text-muted")


async def source_delete_page(source_id: str, session_factory: SessionFactoryDep) -> None:
    """Render source deletion confirmation workspace."""
    sources_service = TranscriptionService(session_factory=session_factory)
    parsed_source_id: UUID | None = None
    try:
        parsed_source_id = UUID(source_id)
    except ValueError:
        parsed_source_id = None

    is_linked = False
    if parsed_source_id is not None:
        try:
            source = await sources_service.read_source_detail(parsed_source_id)
            is_linked = bool(source.job_sources)
        except TranscriptionNotFoundError:
            is_linked = False
        except Exception as exc:  # noqa: BLE001
            show_error(exc, title="Load failed", operation="sources.delete.read")
            return

    render_navigation_header(current_path="/sources")

    with ui.column().classes("w-full max-w-7xl mx-auto p-6 gap-6"):
        with archival_card(title="Delete Source Confirmation"):
            if parsed_source_id is None:
                ui.label("Invalid source id").classes("text-h6 ui-text-danger p-4")
                return
            if is_linked:
                ui.label("Cannot delete source linked to active jobs.").classes("ui-text-danger")
            else:
                ui.label(f"Are you sure you want to delete source {source_id}?").classes("ui-text-muted")


def register_page() -> None:
    """Register all source-related UI routes with the application router."""
    ui.page("/sources")(sources_page)
    ui.page("/sources/{source_id}")(source_detail_page)
    ui.page("/sources/{source_id}/delete")(source_delete_page)