"""Pin detail panel for the selected connector version."""

from __future__ import annotations

from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.components import (
    H2,
    Button,
    CardContent,
    CardHeader,
    Column,
    DataTable,
    DataTableColumn,
    Dialog,
    Div,
    Link,
    Markdown,
    Muted,
    Row,
    Text,
)
from prefab_ui.components.control_flow import If
from prefab_ui.rx import EVENT, RESULT, STATE

from airbyte_ops_webapp.pages.connector_version_manager._helpers import (
    EMPTY_PIN_STATE,
    fail_tool_call,
    finish_tool_call,
    start_tool_call,
)
from airbyte_ops_webapp.pages.connector_version_manager._mcp_tools import (
    load_version_pins,
    remove_selected_pins,
)
from airbyte_ops_webapp.theme import (
    BUTTON_DESTRUCTIVE_CLASS,
    BUTTON_INFO_CLASS,
    BUTTON_OUTLINE_CLASS,
    PANEL_CARD_CLASS,
    _card_style,
)

# ---------------------------------------------------------------------------
# Pin-load success actions
# ---------------------------------------------------------------------------

_PIN_LOAD_SUCCESS = [
    *finish_tool_call(),
    SetState("version_pins", RESULT.version_pins),
    SetState("version_pins_total", RESULT.version_pins_total),
    SetState("version_pins_offset", RESULT.version_pins_offset),
    SetState("show_load_more_pins", RESULT.show_load_more_pins),
    SetState("all_pins_loaded", RESULT.all_pins_loaded),
    SetState("selected_version_id", RESULT.selected_version_id),
    SetState("selected_version_tag", RESULT.selected_version_tag),
    SetState("selected_pin_index", -1),
    SetState("selected_pin_checks", []),
    SetState("selected_pin", EMPTY_PIN_STATE),
]

_PIN_REMOVAL_SUCCESS = [
    *finish_tool_call(),
    SetState("version_pins", RESULT.version_pins),
    SetState("version_pins_total", RESULT.version_pins_total),
    SetState("version_pins_offset", RESULT.version_pins_offset),
    SetState("show_load_more_pins", RESULT.show_load_more_pins),
    SetState("all_pins_loaded", RESULT.all_pins_loaded),
    SetState("selected_version_id", RESULT.selected_version_id),
    SetState("selected_version_tag", RESULT.selected_version_tag),
    SetState("selected_pin_index", -1),
    SetState("selected_pin_checks", []),
    SetState("selected_pin", EMPTY_PIN_STATE),
    ShowToast(RESULT.remove_message),
]


# ---------------------------------------------------------------------------
# Public render
# ---------------------------------------------------------------------------


def render_pin_detail() -> None:
    """Separate card section showing pin detail for the selected version."""
    with (
        If(STATE.selected_version_tag),
        Div(css_class=PANEL_CARD_CLASS, style=_card_style()),
    ):
        with CardHeader():
            H2(
                STATE.selected_version_tag
                + " — "
                + STATE.version_pins_total.number()
                + " pin(s)",
                style={"fontSize": "1.1rem"},
            )
        with CardContent():
            _render_pin_table_with_checkboxes()
            _render_pin_action_buttons()


# ---------------------------------------------------------------------------
# Pin detail sub-sections
# ---------------------------------------------------------------------------


def _render_pin_table_with_checkboxes() -> None:
    """Pin list table with checkboxes for bulk selection."""
    with If(STATE.version_pins_total):
        with Div(style={"maxHeight": "280px", "overflowY": "auto"}):
            DataTable(
                columns=[
                    DataTableColumn(key="scope_type", header="Scope"),
                    DataTableColumn(key="scope_id", header="Scope ID"),
                    DataTableColumn(key="description_display", header="Reason"),
                    DataTableColumn(key="created_at_display", header="Date"),
                    DataTableColumn(key="expires_at_display", header="Expires"),
                ],
                rows=STATE.version_pins,
                pageSize=10,
                selectable=True,
                on_selection_change=[
                    SetState("selected_pin_checks", EVENT),
                ],
                on_row_click=[
                    SetState("selected_pin", EVENT),
                    SetState("context_guid", EVENT.scope_id),
                ],
            )
        _render_selected_pin_detail()
    with If(STATE.version_pins_total.__eq__(0)):
        Muted("No pins for this version.")


def _render_selected_pin_detail() -> None:
    """Show clickable scope link and full description for selected pin."""
    with (
        If(STATE.selected_pin.scope_id),
        Row(
            gap=3,
            style={
                "marginTop": "0.5rem",
                "padding": "0.5rem",
                "backgroundColor": "#f9fafb",
                "borderRadius": "4px",
                "fontSize": "0.85rem",
            },
        ),
    ):
        with If(STATE.selected_pin.scope_url):
            Link(
                content=STATE.selected_pin.scope_id,
                href=STATE.selected_pin.scope_url,
                target="_blank",
                style={"fontWeight": "500"},
            )
        with If(STATE.selected_pin.description):
            Text(
                content=STATE.selected_pin.description,
                style={"color": "#6b7280"},
            )


def _render_pin_action_buttons() -> None:
    """Bottom action row: left = Add Pins / Remove Selected, right = indicator + Load More."""
    with Row(justify="between", gap=2, style={"marginTop": "0.5rem"}):
        # Left-aligned action buttons
        with Row(gap=2):
            Button(
                "Add Pins...",
                variant="default",
                size="sm",
                css_class=BUTTON_INFO_CLASS,
                on_click=[
                    SetState("pin_modal_open", True),
                    SetState("action", "set"),
                    SetState("target_version", STATE.selected_version_tag),
                ],
            )
            _render_remove_selected_button()

        # Right-aligned: "N of M pins loaded" indicator + Load More button.
        # Hidden when total fits in one batch; disabled when all rows loaded.
        with (
            If(STATE.show_load_more_pins.__eq__(True)),
            Row(gap=2, style={"alignItems": "center"}),
        ):
            Muted(
                STATE.version_pins.length().number()
                + " of "
                + STATE.version_pins_total.number()
                + " pins loaded",
            )
            Button(
                "Load More Pins",
                variant="outline",
                size="sm",
                css_class=BUTTON_OUTLINE_CLASS,
                disabled=STATE.all_pins_loaded.__eq__(True),
                on_click=[
                    *start_tool_call("Loading more pins…"),
                    CallTool(
                        load_version_pins,
                        arguments={
                            "version_id": STATE.selected_version_id,
                            "version_tag": STATE.selected_version_tag,
                            "auth_bearer_token": STATE.auth_bearer_token,
                            "offset": STATE.version_pins_offset,
                        },
                        on_success=_PIN_LOAD_SUCCESS,
                        on_error=fail_tool_call("Failed to load more pins."),
                    ),
                ],
            )


def _render_remove_selected_button() -> None:
    """Remove Selected button with confirmation modal."""
    with Dialog(
        title="Confirm Pin Removal",
        description="This action cannot be undone.",
        name="remove_pins_modal_open",
    ):
        Button(
            "Remove Selected",
            variant="destructive",
            size="sm",
            css_class=BUTTON_DESTRUCTIVE_CLASS,
        )

        with Column(gap=4):
            Markdown(
                content="**Confirm removing selected pins?**\n\n"
                "This will unset version overrides for the selected "
                "scopes. This action cannot be undone."
            )
            with Row(justify="end", gap=2):
                Button(
                    "Cancel",
                    variant="outline",
                    css_class=BUTTON_OUTLINE_CLASS,
                    on_click=[SetState("remove_pins_modal_open", False)],
                )
                Button(
                    "Confirm",
                    variant="destructive",
                    css_class=BUTTON_DESTRUCTIVE_CLASS,
                    disabled=STATE.is_loading,
                    on_click=[
                        SetState("remove_pins_modal_open", False),
                        *start_tool_call("Removing selected pins…"),
                        CallTool(
                            remove_selected_pins,
                            arguments={
                                "selected_pins": STATE.selected_pin_checks,
                                "connector_id": STATE.selected_connector.id,
                                "connector_name": (STATE.selected_connector.name),
                                "connector_type": (
                                    STATE.selected_connector.connector_type
                                ),
                                "version_id": STATE.selected_version_id,
                                "version_tag": STATE.selected_version_tag,
                                "auth_bearer_token": STATE.auth_bearer_token,
                                "user_email": STATE.oauth_user_email,
                            },
                            on_success=_PIN_REMOVAL_SUCCESS,
                            on_error=fail_tool_call("Failed to remove selected pins."),
                        ),
                    ],
                )
