from nicegui import ui

from nemo_library_etl.adapter.migman.config_store import get_config_differences

from ..render_context import UIRenderContext


def render_overview(ctx: UIRenderContext) -> None:
    runtime = ctx.runtime
    global_config = runtime.global_config
    local_config = runtime.local_config
    merged_config = runtime.merged_config
    form_state = runtime.form_state
    state = runtime.state
    has_changes = runtime.has_changes
    active = runtime.active
    nav_buttons = runtime.nav_buttons
    controller = ctx.controller
    content_container = ctx.content_container
    transform_tab_state = ctx.transform_tab_state
    convenience_hooks = ctx.convenience_hooks
    migmanprojects = ctx.migmanprojects
    get_tip = ctx.get_tip
    mark_changed = ctx.mark_changed
    mark_saved = ctx.mark_saved
    set_active = ctx.set_active
    save_config = ctx.save_config
    reset_config = ctx.reset_config
    renderers = ctx.renderers
    self = ctx.ui_app

    def render_overview():
        if not content_container:
            return

        content_container.clear()
        with content_container:
            ui.label("Configuration Overview").classes("text-2xl font-semibold")
            ui.separator()
            ui.label(
                "Review all configuration values that differ from defaults."
            )

            # Reload default configuration to ensure we have the latest defaults
            current_default_config = self.config_store.load_default()
            config_differences = get_config_differences(form_state["data"], current_default_config)
      
            if not config_differences:
                with ui.card().classes("mt-4 p-6 text-center"):
                    ui.icon("check_circle", size="3rem").classes(
                        "text-green-500 mb-2"
                    )
                    ui.label("All settings are using default values").classes(
                        "text-lg font-medium"
                    )
                    ui.label(
                        "No custom configuration has been applied."
                    ).classes("text-gray-600")
                return

            def render_config_section(config_data, section_name="", level=0):
                """Recursively render configuration sections."""
                indent_class = f"ml-{level * 4}" if level > 0 else ""

                for key, value in config_data.items():
                    if isinstance(value, dict) and value:
                        # Render subsection header
                        section_title = (
                            f"{section_name}.{key}" if section_name else key
                        )
                        with ui.card().classes(f"mt-3 {indent_class}"):
                            ui.label(section_title.title()).classes(
                                "text-lg font-semibold mb-2"
                            )
                            render_config_section(
                                value, section_title, level + 1
                            )
                    elif not isinstance(value, dict):
                        # Render individual setting
                        setting_name = (
                            f"{section_name}.{key}" if section_name else key
                        )
                        with ui.row().classes(
                            f"items-center gap-4 p-2 {indent_class}"
                        ):
                            ui.label(key).classes("font-medium min-w-48")

                            # Format value display based on type
                            if isinstance(value, bool):
                                ui.chip(
                                    str(value),
                                    color="green" if value else "red",
                                ).props("outline")
                            elif isinstance(value, list):
                                if value:
                                    ui.label(f"[{len(value)} items]").classes(
                                        "text-gray-600"
                                    )
                                    with ui.column().classes("ml-4"):
                                        for item in value[
                                            :5
                                        ]:  # Show first 5 items
                                            ui.label(f"• {str(item)}").classes(
                                                "text-sm text-gray-700"
                                            )
                                        if len(value) > 5:
                                            ui.label(
                                                f"... and {len(value) - 5} more"
                                            ).classes("text-sm text-gray-500")
                                else:
                                    ui.label("[]").classes("text-gray-600")
                            elif isinstance(value, str):
                                if len(str(value)) > 60:
                                    ui.label(f"{str(value)[:60]}...").classes(
                                        "text-gray-700 font-mono text-sm"
                                    )
                                else:
                                    ui.label(str(value)).classes(
                                        "text-gray-700 font-mono text-sm"
                                    )
                            else:
                                ui.label(str(value)).classes("text-gray-700")

            with ui.card().classes("mt-4"):
                ui.label("Custom Configuration Settings").classes(
                    "text-lg font-semibold mb-4"
                )
                render_config_section(config_differences)

    render_overview()
