"""Upload page registration and handlers."""

from __future__ import annotations

from dataclasses import dataclass

from nicegui import ui
from nicegui.events import UploadEventArguments

from transcription.services.upload import UploadError, UploadJobResult, create_upload_job
from transcription.ui.error_presenter import show_error, summarize_error


@dataclass
class UploadPageState:
    """Simple state container for upload page feedback."""

    loading: bool = False
    message: str = ""


def accepted_upload_types() -> str:
    """Return accepted file type string for upload input."""
    return ".jpg,.jpeg,.png,.tif,.tiff,.pdf"


def submit_upload(*, filename: str, file_bytes: bytes) -> UploadJobResult:
    """Create an upload job from incoming file data."""
    return create_upload_job(filename=filename, file_bytes=file_bytes)


def register_page() -> None:
    """Register the upload page route."""

    @ui.page("/")
    def upload_page() -> None:
        state = UploadPageState()
        status_label = ui.label("Upload a document to start transcription.")

        async def on_upload(event: UploadEventArguments) -> None:
            if state.loading:
                ui.notify("Upload already in progress. Please wait.", type="warning")
                return

            state.loading = True
            status_label.text = "Uploading..."
            try:
                payload = await event.file.read()
                result = submit_upload(filename=event.file.name, file_bytes=payload)
                state.message = f"Created job {result.job_id}"
                status_label.text = state.message
                ui.notify(state.message, type="positive")
            except UploadError as exc:
                state.message = summarize_error(exc, operation="upload.submit")
                status_label.text = f"Upload failed: {state.message}"
                show_error(exc, title="Upload failed", operation="upload.submit")
            except Exception as exc:  # noqa: BLE001
                state.message = summarize_error(exc, operation="upload.submit")
                status_label.text = f"Upload failed: {state.message}"
                show_error(exc, title="Upload failed", operation="upload.submit")
            finally:
                state.loading = False

        ui.upload(
            on_upload=on_upload,
            auto_upload=True,
            label="Select document file",
        ).props(f"accept={accepted_upload_types()}")

        with ui.row():
            ui.link("View jobs", "/jobs")
