"""Table component for displaying and managing OpenAI skills."""

import reflex as rx

import appkit_mantine as mn
from appkit_assistant.backend.database.models import Skill
from appkit_assistant.components.skill_dialogs import (
    create_skill_modal,
    delete_skill_dialog,
)
from appkit_assistant.state.skill_admin_state import SkillAdminState
from appkit_ui.styles import sticky_header_style


def _skill_table_row(skill: Skill) -> rx.Component:
    """Render a single skill row."""
    return mn.table.tr(
        mn.table.td(
            mn.text(skill.name, size="sm", fw="500", style={"whiteSpace": "nowrap"}),
            min_width="200px",
        ),
        mn.table.td(
            mn.text(
                skill.description,
                size="sm",
                c="dimmed",
                line_clamp=2,
                title=skill.description,
            ),
        ),
        mn.table.td(
            mn.group(
                mn.select(
                    value=skill.required_role,
                    data=SkillAdminState.available_roles,
                    placeholder="nicht eingeschränkt",
                    size="xs",
                    clearable=True,
                    check_icon_position="right",
                    on_change=lambda val: SkillAdminState.update_skill_role(
                        skill.id, val
                    ),
                    w="160px",
                ),
                mn.box(
                    rx.cond(
                        SkillAdminState.updating_role_skill_id == skill.id,
                        rx.spinner(size="1"),
                    ),
                    width="16px",
                    display="flex",
                    align_items="center",
                    justify_content="center",
                    flex_shrink="0",
                ),
                align="center",
                gap="xs",
                wrap="nowrap",
            ),
            width="1%",
            style={"whiteSpace": "nowrap"},
        ),
        mn.table.td(
            mn.group(
                mn.switch(
                    checked=skill.active,
                    on_change=lambda checked: SkillAdminState.toggle_skill_active(
                        skill.id, checked
                    ),
                    size="sm",
                ),
                mn.box(
                    rx.cond(
                        SkillAdminState.updating_active_skill_id == skill.id,
                        rx.spinner(size="1"),
                    ),
                    width="16px",
                    display="flex",
                    align_items="center",
                    justify_content="center",
                    flex_shrink="0",
                ),
                align="center",
                gap="xs",
                wrap="nowrap",
            ),
            width="1%",
            style={"whiteSpace": "nowrap"},
        ),
        mn.table.td(
            rx.hstack(
                delete_skill_dialog(skill),
                spacing="2",
                align_items="center",
            ),
            width="1%",
            style={"whiteSpace": "nowrap"},
        ),
    )


def skills_table(
    role_labels: dict[str, str] | None = None,
    available_roles: list[dict[str, str]] | None = None,
    load_on_mount: bool = False,
) -> rx.Component:
    """Admin table for managing OpenAI skills.

    Args:
        role_labels: Mapping of role names to display labels.
        available_roles: List of available roles for filtering.
        load_on_mount: If True, load skills on component mount.
            Default is False (lazy load via admin page).
    """
    if role_labels is None:
        role_labels = {}
    if available_roles is None:
        available_roles = []

    return mn.stack(
        rx.flex(
            mn.button(
                "Neuen Skill anlegen",
                left_section=rx.icon("plus", size=16),
                size="sm",
                on_click=SkillAdminState.open_create_modal,
                disabled=~SkillAdminState.has_skill_models,
            ),
            mn.text_input(
                placeholder="Skills filtern...",
                left_section=rx.icon("search", size=16),
                left_section_pointer_events="none",
                value=SkillAdminState.search_filter,
                on_change=SkillAdminState.set_search_filter,
                size="sm",
                w="18rem",
            ),
            rx.spacer(),
            mn.select(
                data=SkillAdminState.skill_model_options,
                value=SkillAdminState.selected_model_id,
                on_change=SkillAdminState.set_selected_model,
                placeholder="Modell auswählen...",
                size="sm",
                w="14rem",
            ),
            mn.button(
                "Synchronisieren",
                left_section=rx.icon("refresh-cw", size=16),
                size="sm",
                variant="outline",
                on_click=SkillAdminState.sync_skills,
                loading=SkillAdminState.syncing,
                disabled=~SkillAdminState.has_skill_models,
            ),
            width="100%",
            margin_bottom="md",
            gap="12px",
            align="center",
        ),
        create_skill_modal(),
        rx.box(
            mn.loading_overlay(
                visible=SkillAdminState.loading | SkillAdminState.syncing,
                overlayProps={"min_height": "200px"},
            ),
            mn.table(
                mn.table.thead(
                    mn.table.tr(
                        mn.table.th(mn.text("Name", size="sm", fw="700")),
                        mn.table.th(mn.text("Beschreibung", size="sm", fw="700")),
                        mn.table.th(mn.text("Rolle", size="sm", fw="700")),
                        mn.table.th(mn.text("Aktiv", size="sm", fw="700")),
                        mn.table.th(mn.text("", size="sm")),
                        style=sticky_header_style,
                    ),
                ),
                mn.table.tbody(
                    rx.foreach(
                        SkillAdminState.filtered_skills,
                        _skill_table_row,
                    )
                ),
                sticky_header=True,
                sticky_header_offset="0px",
                striped=False,
                highlight_on_hover=True,
                highlight_on_hover_color=rx.color_mode_cond(
                    light="gray.0",
                    dark="dark.8",
                ),
                w="100%",
            ),
            position="relative",
            w="100%",
            min_height="200px",
        ),
        w="100%",
        on_mount=(
            lambda: (
                [
                    SkillAdminState.set_available_roles(available_roles, role_labels),
                    SkillAdminState.load_skill_models() if load_on_mount else None,
                    SkillAdminState.load_skills_with_toast() if load_on_mount else None,
                ]
                if load_on_mount
                else [SkillAdminState.set_available_roles(available_roles, role_labels)]
            )
        ),
    )
