"""Homepage registration and handlers."""

from __future__ import annotations

from nicegui import ui

from transcription.ui.components.app_shell import render_navigation_header
from transcription.ui.components.cards import archival_card
from transcription.ui.components.primitives import render_empty_state
from transcription.ui.components.primitives import section_header_row
from transcription.ui.components.viewers import dark_room_viewer
from transcription.ui.homepage_store import latest_homepage_image
from transcription.ui.homepage_store import read_homepage_markdown
from transcription.ui.homepage_store import save_homepage_markdown
from transcription.ui.homepage_store import store_homepage_image
from transcription.ui.theme import page_header


def _render_homepage_view(*, markdown_text: str, image_path) -> None:
    with ui.grid().classes("w-full grid-cols-12 gap-4"):
        with ui.column().classes("col-span-12 lg:col-span-4"):
            dark_room_viewer(str(image_path) if image_path else None, count_label="Homepage Image")

        with ui.column().classes("col-span-12 lg:col-span-5 gap-4"), archival_card(title="Home Text"):
            if markdown_text:
                ui.markdown(markdown_text)
            else:
                render_empty_state("No homepage text saved yet.")

        with ui.column().classes("col-span-12 lg:col-span-3"):
            ui.element("div")


def _render_homepage_editor(*, render_image_panel, markdown_input, on_upload) -> None:
    with ui.grid().classes("w-full grid-cols-12 gap-4"):
        with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
            with archival_card(title="Homepage Image"):
                ui.upload(on_upload=on_upload, auto_upload=True, label="Upload image").props(
                    'accept=".jpg,.jpeg,.png,.gif,.webp,.bmp,.tif,.tiff"'
                ).classes("w-full")
            render_image_panel()

        with ui.column().classes("col-span-12 lg:col-span-5 gap-4"), archival_card(title="Home Text"):
            markdown_input[0] = ui.textarea(
                label="Homepage markdown",
                value=read_homepage_markdown(),
            ).props("outlined autogrow").classes("w-full")

        with ui.column().classes("col-span-12 lg:col-span-3"):
            ui.element("div")


def register_page() -> None:
    """Register the homepage routes."""

    @ui.page("/homepage", title="VibeScribe Home")
    def homepage_page() -> None:
        render_navigation_header(current_path="/homepage")

        with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
            with section_header_row():
                page_header("Home")
                ui.button(
                    "Edit Home Page",
                    on_click=lambda: ui.navigate.to("/homepage/edit"),
                    icon="edit",
                ).classes("ui-btn-primary text-xs")

            _render_homepage_view(
                markdown_text=read_homepage_markdown().strip(),
                image_path=latest_homepage_image(),
            )

    @ui.page("/homepage/edit", title="Edit Homepage")
    def homepage_edit_page() -> None:
        render_navigation_header(current_path="/homepage")

        preview_image = [latest_homepage_image()]
        markdown_input = [None]

        @ui.refreshable
        def render_image_panel() -> None:
            dark_room_viewer(str(preview_image[0]) if preview_image[0] else None, count_label="Homepage Image")

        async def on_upload(event) -> None:
            payload = await event.file.read()
            preview_image[0] = store_homepage_image(filename=event.file.name, file_bytes=payload)
            ui.notify(f"Uploaded {event.file.name}", type="positive")
            render_image_panel.refresh()

        async def save_homepage() -> None:
            save_homepage_markdown((markdown_input[0].value if markdown_input[0] is not None else "") or "")
            ui.notify("Homepage saved", type="positive")
            ui.navigate.to("/homepage")

        with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
            with section_header_row():
                page_header("Edit Home Page")
                with ui.row().classes("items-center gap-2"):
                    ui.button("Save", on_click=save_homepage, icon="save").classes("ui-btn-primary text-xs")
                    ui.button("Cancel", on_click=lambda: ui.navigate.to("/homepage"), icon="close").props("flat")

            _render_homepage_editor(
                render_image_panel=render_image_panel,
                markdown_input=markdown_input,
                on_upload=on_upload,
            )
