"""Field selection component with file picker and path list."""
from pathlib import Path

from nicegui import ui

from .local_file_picker import LocalFilePicker


# -----------------------------------------------------------------------------
# Public API
# -----------------------------------------------------------------------------

def field_selector(fields: list[str], on_change=None) -> None:
    """Render field selection UI: list of paths + Add/Remove buttons."""
    container = ui.column().classes("w-full")

    def refresh_list() -> None:
        container.clear()
        with container:
            if not fields:
                ui.label("No fields selected").classes("text-gray-500 italic")
            else:
                for i, path in enumerate(fields):
                    with ui.row().classes("items-center gap-2 w-full"):
                        ui.label(Path(path).name).classes("flex-1 truncate")
                        ui.button(
                            icon="delete",
                            on_click=lambda idx=i: remove_field(idx),
                        ).props("flat round dense color=negative")

            with ui.row().classes("mt-2"):
                ui.button(
                    "Add field",
                    icon="add",
                    on_click=add_field,
                ).props("outline")

    async def add_field() -> None:
        picker = LocalFilePicker(
            str(Path.home()),
            multiple=True,
        )
        result = await picker
        if result:
            for p in result:
                if p not in fields:
                    fields.append(p)
            refresh_list()
            on_change and on_change()

    def remove_field(index: int) -> None:
        if 0 <= index < len(fields):
            fields.pop(index)
            refresh_list()
            on_change and on_change()

    refresh_list()
