"""Status bubble composite aligned with Smartbank Figma design system.

Provides status bubble components for displaying transaction and payment
status with colored backgrounds and status indicators.

Figma reference: node-id=16625:53297 (status-bubble frame)
"""

from __future__ import annotations

from typing import Literal

import pydivkit as dk

from smarty_ui.tokens.theme import Theme, default_theme

StatusType = Literal["success", "error", "pending"]
BubbleType = Literal["transfer", "payment"]


# Status colors mapping
STATUS_COLORS = {
    "success": {
        "gradient_start": "#076AE2",
        "gradient_end": "#035DCA",
        "use_gradient": True,
    },
    "error": {
        "solid": "#FF516E",
        "use_gradient": False,
    },
    "pending": {
        "solid": "#80858E",
        "use_gradient": False,
    },
}

# Status labels mapping
STATUS_LABELS = {
    "transfer": {
        "success": "Перевод выполнен",
        "error": "Ошибка при переводе",
        "pending": "Ожидание",
    },
    "payment": {
        "success": "Оплата успешно выполнена",
        "error": "Ошибка при оплате",
        "pending": "Ожидание",
    },
}


def _build_background(status: StatusType) -> list[dk.DivBackground]:
    """Build background based on status type."""
    config = STATUS_COLORS[status]

    if config.get("use_gradient"):
        return [
            dk.DivLinearGradient(
                angle=180,
                colors=[config["gradient_start"], config["gradient_end"]],
            )
        ]
    else:
        return [dk.DivSolidBackground(color=config["solid"])]


def _build_status_icon(
    status: StatusType,
    icon_url: str | None = None,
    *,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Build the status icon container.

    For transfers: shows a checkmark (success), X (error), or clock (pending)
    For payments: shows the merchant/service icon in a circular container
    """
    icon_size = 48
    inner_icon_size = 24

    # If custom icon URL provided (for payments), show it in a circular container
    if icon_url:
        return dk.DivContainer(
            orientation=dk.DivContainerOrientation.HORIZONTAL,
            content_alignment_horizontal=dk.DivContentAlignmentHorizontal.CENTER,
            content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
            width=dk.DivFixedSize(value=icon_size),
            height=dk.DivFixedSize(value=icon_size),
            border=dk.DivBorder(
                corner_radius=icon_size // 2,
                stroke=dk.DivStroke(color=theme.colors.grey_medium, width=1),
            ),
            background=[dk.DivSolidBackground(color=theme.colors.grey_light)],
            items=[
                dk.DivImage(
                    image_url=icon_url,
                    width=dk.DivFixedSize(value=34),
                    height=dk.DivFixedSize(value=34),
                    scale=dk.DivImageScale.FIT,
                )
            ],
        )

    # For transfers without custom icon, show status indicator
    # Using text symbols as fallback (ideally would use icon URLs)
    status_symbols = {
        "success": "✓",
        "error": "✕",
        "pending": "⏱",
    }

    # Get background color based on status for opaque icon background
    status_bg_colors = {
        "success": "#0560C9",  # Slightly darker blue to blend with gradient
        "error": "#E6475F",  # Slightly darker red
        "pending": "#6E737A",  # Slightly darker grey
    }
    icon_bg_color = status_bg_colors.get(status, "#0560C9")

    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_horizontal=dk.DivContentAlignmentHorizontal.CENTER,
        content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
        width=dk.DivFixedSize(value=icon_size),
        height=dk.DivFixedSize(value=icon_size),
        border=dk.DivBorder(
            corner_radius=icon_size // 2,
            stroke=dk.DivStroke(color="#FFFFFF", width=1),
        ),
        background=[dk.DivSolidBackground(color=icon_bg_color)],
        items=[
            dk.DivText(
                text=status_symbols.get(status, ""),
                font_size=inner_icon_size,
                font_weight=dk.DivFontWeight("bold"),
                text_color="#FFFFFF",
                width=dk.DivWrapContentSize(),
                text_alignment_horizontal=dk.DivAlignmentHorizontal.CENTER,
            )
        ],
    )


def status_bubble(
    amount: str,
    *,
    status: StatusType = "success",
    bubble_type: BubbleType = "transfer",
    recipient: str | None = None,
    date_time: str | None = None,
    card_info: str | None = None,
    icon_url: str | None = None,
    currency: str = "сум",
    width: int = 350,
    height: int = 142,
    corner_radius: int = 16,
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Status bubble component for transaction/payment status.

    A colored card with:
    - Status label (top left)
    - Status icon (top right)
    - Amount (large text)
    - Recipient info
    - Date/time or card info

    Design specs (from Figma):
    - Width: 350px
    - Height: 142px
    - Corner radius: 16px
    - Padding: 20px
    - Background: gradient (success), solid red (error), solid grey (pending)
    - All text is white

    Args:
        amount: Formatted amount string (e.g., "200 000")
        status: Status type - "success", "error", or "pending"
        bubble_type: Type of bubble - "transfer" or "payment"
        recipient: Recipient name/info (e.g., "ALEKSANDR GURYANOV ** 2221")
        date_time: Date and time string (e.g., "3 сентября 2023 18:27")
        card_info: Card info for payments (e.g., "Карта списания: ·· 6847")
        icon_url: Optional icon URL for payment merchant/service
        currency: Currency suffix (default "сум")
        width: Widget width (default 350)
        height: Widget height (default 142)
        corner_radius: Border radius (default 16)
        action_url: Optional URL to navigate on tap
        theme: Theme tokens to use

    Returns:
        A DivContainer representing the status bubble
    """
    # Get typography styles
    caption_style = theme.typography.get_caption_1()  # SemiBold 12px
    title_style = theme.typography.get_title_1()  # Bold 26px

    # Get status label
    status_label = STATUS_LABELS.get(bubble_type, {}).get(status, "")

    # Build content items
    content_items: list[dk.Div] = []

    # Row 1: Status label + icon
    header_row = dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
        width=dk.DivMatchParentSize(),
        items=[
            # Status label
            dk.DivText(
                text=status_label,
                font_size=caption_style.size,
                font_weight=dk.DivFontWeight(caption_style.weight),
                text_color="#FFFFFF",
                line_height=caption_style.line_height,
                width=dk.DivMatchParentSize(weight=1),
            ),
            # Status icon
            _build_status_icon(status, icon_url, theme=theme),
        ],
    )
    content_items.append(header_row)

    # Row 2: Amount
    amount_text = dk.DivText(
        text=f"{amount} {currency}",
        font_size=title_style.size,
        font_weight=dk.DivFontWeight(title_style.weight),
        text_color="#FFFFFF",
        line_height=title_style.line_height,
        width=dk.DivMatchParentSize(),
        margins=dk.DivEdgeInsets(top=2),
    )
    content_items.append(amount_text)

    # Row 3: Recipient info
    if recipient:
        recipient_text = dk.DivText(
            text=recipient,
            font_size=caption_style.size,
            font_weight=dk.DivFontWeight(caption_style.weight),
            text_color="#FFFFFF",
            line_height=caption_style.line_height,
            width=dk.DivMatchParentSize(),
            margins=dk.DivEdgeInsets(top=8),
        )
        content_items.append(recipient_text)

    # Row 4: Date/time or card info
    if date_time:
        date_text = dk.DivText(
            text=date_time,
            font_size=caption_style.size,
            font_weight=dk.DivFontWeight(caption_style.weight),
            text_color="#FFFFFF",
            line_height=caption_style.line_height,
            width=dk.DivMatchParentSize(),
            margins=dk.DivEdgeInsets(top=4),
        )
        content_items.append(date_text)

    if card_info:
        card_text = dk.DivText(
            text=card_info,
            font_size=caption_style.size,
            font_weight=dk.DivFontWeight(caption_style.weight),
            text_color="#FFFFFF",
            line_height=caption_style.line_height,
            width=dk.DivMatchParentSize(),
            margins=dk.DivEdgeInsets(top=4),
        )
        content_items.append(card_text)

    # Build action if URL provided
    actions = None
    if action_url:
        actions = [dk.DivAction(log_id=f"status_bubble_{status}", url=action_url)]

    # Build main container
    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivFixedSize(value=width),
        height=dk.DivFixedSize(value=height + 10),
        border=dk.DivBorder(corner_radius=corner_radius),
        background=_build_background(status),
        paddings=dk.DivEdgeInsets(
            left=20,
            right=20,
            top=20,
            bottom=20,
        ),
        actions=actions,
        items=content_items,
    )


def transfer_success_bubble(
    amount: str,
    recipient: str,
    date_time: str,
    *,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for successful transfer status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient name/card info
        date_time: Transaction date and time
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for successful transfer
    """
    return status_bubble(
        amount,
        status="success",
        bubble_type="transfer",
        recipient=recipient,
        date_time=date_time,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )


def transfer_error_bubble(
    amount: str,
    recipient: str,
    date_time: str,
    *,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for failed transfer status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient name/card info
        date_time: Transaction date and time
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for failed transfer
    """
    return status_bubble(
        amount,
        status="error",
        bubble_type="transfer",
        recipient=recipient,
        date_time=date_time,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )


def transfer_pending_bubble(
    amount: str,
    recipient: str,
    date_time: str,
    *,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for pending transfer status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient name/card info
        date_time: Transaction date and time
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for pending transfer
    """
    return status_bubble(
        amount,
        status="pending",
        bubble_type="transfer",
        recipient=recipient,
        date_time=date_time,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )


def payment_success_bubble(
    amount: str,
    recipient: str,
    card_info: str,
    *,
    icon_url: str | None = None,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for successful payment status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient/phone number
        card_info: Card info (e.g., "Карта списания: ·· 6847")
        icon_url: Optional merchant/service icon URL
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for successful payment
    """
    return status_bubble(
        amount,
        status="success",
        bubble_type="payment",
        recipient=recipient,
        card_info=card_info,
        icon_url=icon_url,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )


def payment_error_bubble(
    amount: str,
    recipient: str,
    card_info: str,
    *,
    icon_url: str | None = None,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for failed payment status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient/phone number
        card_info: Card info
        icon_url: Optional merchant/service icon URL
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for failed payment
    """
    return status_bubble(
        amount,
        status="error",
        bubble_type="payment",
        recipient=recipient,
        card_info=card_info,
        icon_url=icon_url,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )


def payment_pending_bubble(
    amount: str,
    recipient: str,
    card_info: str,
    *,
    icon_url: str | None = None,
    currency: str = "сум",
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Convenience function for pending payment status bubble.

    Args:
        amount: Formatted amount string
        recipient: Recipient/phone number
        card_info: Card info
        icon_url: Optional merchant/service icon URL
        currency: Currency suffix
        action_url: Optional tap action URL
        theme: Theme tokens to use

    Returns:
        A status bubble for pending payment
    """
    return status_bubble(
        amount,
        status="pending",
        bubble_type="payment",
        recipient=recipient,
        card_info=card_info,
        icon_url=icon_url,
        currency=currency,
        action_url=action_url,
        theme=theme,
    )
