"""Confirmation dialog shown before applying billing changes."""

from __future__ import annotations

from prefab_ui.actions import SetState
from prefab_ui.actions.mcp import CallTool
from prefab_ui.components import (
    Button,
    Column,
    Dialog,
    Grid,
    Markdown,
    Row,
    Text,
)
from prefab_ui.components.control_flow import If
from prefab_ui.rx import STATE

from airbyte_ops_webapp.pages.customer_billing._helpers import (
    apply_fail_actions,
    apply_success_actions,
    start_tool_call,
)
from airbyte_ops_webapp.pages.customer_billing._mcp_tools import (
    apply_grace_period,
    apply_permanent_waiver,
)
from airbyte_ops_webapp.theme import BUTTON_DESTRUCTIVE_CLASS, BUTTON_INFO_CLASS


def render_confirm_dialog() -> None:
    """Render the pre-apply confirmation dialog.

    Opened when the user clicks Apply on either the Grace Period or Permanent
    Waiver tab. Shows a summary of the pending action and requires explicit
    confirmation before the tool call fires.
    """
    with Dialog(
        title="",
        description="",
        name="confirm_dialog_open",
    ):
        Button("", style={"display": "none"})

        with Column(gap=4):
            Markdown("**Confirm Billing Change**")
            Text(
                "You are about to apply a billing change to a production organization. "
                "Please review the details below before confirming.",
                style={"fontSize": "0.875rem", "opacity": "0.8"},
            )

            _render_grace_period_summary()
            _render_permanent_waiver_summary()

            with Row(justify="end", gap=2):
                Button(
                    "Cancel",
                    variant="info",
                    css_class=BUTTON_INFO_CLASS,
                    on_click=[
                        SetState("confirm_dialog_open", False),
                        SetState("confirm_action_type", ""),
                    ],
                )
                _render_confirm_grace_period_button()
                _render_confirm_waiver_button()


def _render_field(label: str, value: object) -> None:
    """Render a single label-value row in the summary."""
    with Grid(columns=2, gap=2):
        Text(label, style={"fontSize": "0.875rem", "opacity": "0.7"})
        Text(
            content=value,
            style={"fontSize": "0.875rem", "fontWeight": "500"},
        )


def _render_grace_period_summary() -> None:
    """Summary shown when confirming a grace period action."""
    with If(STATE.confirm_action_type == "grace_period"), Column(gap=2):
        _render_field("Organization", STATE.org_info.organization_name)
        _render_field("Action", "Set / Extend / Cancel Grace Period")
        _render_field("Value", STATE.grace_period_value)
        with If(STATE.grace_period_reason):
            _render_field("Reason", STATE.grace_period_reason)


def _render_permanent_waiver_summary() -> None:
    """Summary shown when confirming a permanent waiver action."""
    with If(STATE.confirm_action_type == "permanent_waiver"), Column(gap=2):
        _render_field("Organization", STATE.org_info.organization_name)
        _render_field("Action", "Set / Remove Permanent Waiver")
        _render_field("Waiver Type", STATE.waiver_type)
        with If(STATE.waiver_reason):
            _render_field("Reason", STATE.waiver_reason)


def _render_confirm_grace_period_button() -> None:
    """Confirm button that fires the grace period tool call."""
    with If(STATE.confirm_action_type == "grace_period"):
        Button(
            "Confirm & Apply",
            variant="destructive",
            css_class=BUTTON_DESTRUCTIVE_CLASS,
            on_click=[
                SetState("confirm_dialog_open", False),
                *start_tool_call("Applying grace period change\u2026"),
                CallTool(
                    apply_grace_period,
                    arguments={
                        "organization_id": STATE.payment_config.organization_id,
                        "grace_period_value": STATE.grace_period_value,
                        "reason": STATE.grace_period_reason,
                        "approval_comment_url": STATE.grace_period_approval_url,
                        "organization_name": STATE.org_info.organization_name,
                        "auth_bearer_token": STATE.auth_bearer_token,
                    },
                    on_success=apply_success_actions(),
                    on_error=apply_fail_actions(),
                ),
            ],
        )


def _render_confirm_waiver_button() -> None:
    """Confirm button that fires the permanent waiver tool call."""
    with If(STATE.confirm_action_type == "permanent_waiver"):
        Button(
            "Confirm & Apply",
            variant="destructive",
            css_class=BUTTON_DESTRUCTIVE_CLASS,
            on_click=[
                SetState("confirm_dialog_open", False),
                *start_tool_call("Applying permanent waiver\u2026"),
                CallTool(
                    apply_permanent_waiver,
                    arguments={
                        "organization_id": STATE.payment_config.organization_id,
                        "waiver_type": STATE.waiver_type,
                        "reason": STATE.waiver_reason,
                        "approval_comment_url": STATE.waiver_approval_url,
                        "organization_name": STATE.org_info.organization_name,
                        "auth_bearer_token": STATE.auth_bearer_token,
                    },
                    on_success=apply_success_actions(),
                    on_error=apply_fail_actions(),
                ),
            ],
        )
