"""Send money widget block aligned with Smartbank Figma design system.

Provides a transfer confirmation widget for displaying transfer details
before confirming the transaction.

Figma reference:
- node-id=17519:7240 (Send money confirmation widget)
"""

from __future__ import annotations

from typing import TypedDict

import pydivkit as dk

from smarty_ui.tokens.theme import Theme, default_theme


class RecipientData(TypedDict, total=False):
    """Data structure for recipient information."""

    name: str
    card_last_digits: str | None
    avatar_url: str | None


class SourceCardData(TypedDict, total=False):
    """Data structure for source card information."""

    card_name: str
    card_last_digits: str | None
    card_icon_url: str | None


class SendMoneyData(TypedDict, total=False):
    """Data structure for send money widget."""

    recipient: RecipientData
    source_card: SourceCardData
    amount: str
    currency: str
    button_text: str
    action_url: str | None


def _build_info_row(
    icon_url: str | None,
    label: str,
    value: str,
    *,
    trailing_text: str | None = None,
    icon_size: int = 20,
    icon_bg_size: int = 48,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Build an info row with icon, label, value, and optional trailing text.

    Args:
        icon_url: URL to the icon image
        label: Small label text above the value
        value: Main value text
        trailing_text: Optional text on the right side (e.g., card number)
        icon_size: Size of the icon in dp
        icon_bg_size: Size of the icon background container
        theme: Theme tokens to use

    Returns:
        A DivContainer representing the info row
    """
    items: list[dk.Div] = []

    # Icon in blue-light circle
    if icon_url:
        icon_container = dk.DivContainer(
            orientation=dk.DivContainerOrientation.HORIZONTAL,
            content_alignment_horizontal=dk.DivContentAlignmentHorizontal.CENTER,
            content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
            width=dk.DivFixedSize(value=icon_bg_size),
            height=dk.DivFixedSize(value=icon_bg_size),
            border=dk.DivBorder(corner_radius=icon_bg_size // 2),
            background=[dk.DivSolidBackground(color=theme.colors.blue_light)],
            items=[
                dk.DivImage(
                    image_url=icon_url,
                    width=dk.DivFixedSize(value=icon_size),
                    height=dk.DivFixedSize(value=icon_size),
                    scale=dk.DivImageScale.FIT,
                )
            ],
        )
        items.append(icon_container)

    # Text content (label + value)
    text_items: list[dk.Div] = []

    # Label (Text 02 - Medium 12px, grey-dark)
    text_02_style = theme.typography.get_text_2()
    text_items.append(
        dk.DivText(
            text=label,
            font_size=text_02_style.size,
            font_weight=dk.DivFontWeight(text_02_style.weight),
            text_color=theme.colors.text_secondary,
            line_height=text_02_style.line_height,
            max_lines=1,
            width=dk.DivMatchParentSize(),
        )
    )

    # Value (Controls 02 - Bold 14px, black)
    controls_style = theme.typography.get_controls_2(bold=True)
    text_items.append(
        dk.DivText(
            text=value,
            font_size=controls_style.size,
            font_weight=dk.DivFontWeight(controls_style.weight),
            text_color=theme.colors.text_primary,
            line_height=controls_style.line_height,
            max_lines=1,
            width=dk.DivMatchParentSize(),
            margins=dk.DivEdgeInsets(top=4),
        )
    )

    # Text container
    text_container = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(weight=1),
        margins=dk.DivEdgeInsets(left=12) if icon_url else None,
        items=text_items,
    )
    items.append(text_container)

    # Trailing text (card number)
    if trailing_text:
        items.append(
            dk.DivText(
                text=trailing_text,
                font_size=controls_style.size,
                font_weight=dk.DivFontWeight(controls_style.weight),
                text_color=theme.colors.text_primary,
                line_height=controls_style.line_height,
                width=dk.DivWrapContentSize(),
                margins=dk.DivEdgeInsets(left=8),
            )
        )

    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
        width=dk.DivMatchParentSize(),
        items=items,
    )


def send_money_widget(
    recipient_name: str,
    source_card_name: str,
    amount: str,
    *,
    recipient_card_digits: str | None = None,
    source_card_digits: str | None = None,
    recipient_icon_url: str | None = None,
    source_card_icon_url: str | None = None,
    wallet_icon_url: str | None = None,
    currency: str = "сум",
    button_text: str = "Подтвердить перевод",
    action_url: str | None = None,
    corner_radius: int = 8,
    padding: int = 16,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Send money confirmation widget matching Smartbank Figma design.

    A white card container with:
    - Recipient info row (avatar + name + card digits)
    - Source card info row (card icon + card name + card digits)
    - Amount row (wallet icon + amount)
    - Primary confirm button

    Design specs (from Figma node-id=17519:7240):
    - Width: 327px (flexible)
    - Corner radius: 8px
    - Border: 1px solid #F9F9F9
    - Shadow: 0px 4px 12px rgba(26, 23, 54, 0.05)
    - Icon backgrounds: #EBF2FA (blue-light)
    - Icon size: 48x48px with 24px radius
    - Button: Primary blue (#076AE2)

    Args:
        recipient_name: Name of the recipient
        source_card_name: Name of the source card
        amount: Formatted amount string (e.g., "200 000")
        recipient_card_digits: Last 4 digits of recipient card (e.g., "2221")
        source_card_digits: Last 4 digits of source card (e.g., "6847")
        recipient_icon_url: URL to recipient avatar/icon
        source_card_icon_url: URL to card icon
        wallet_icon_url: URL to wallet icon
        currency: Currency suffix (default "сум")
        button_text: Text for the confirm button
        action_url: URL to navigate on button click
        corner_radius: Border radius (default 8)
        padding: Container padding (default 16)
        theme: Theme tokens to use

    Returns:
        A DivContainer representing the send money widget
    """
    content_items: list[dk.Div] = []

    # Recipient row
    recipient_trailing = f"·· {recipient_card_digits}" if recipient_card_digits else None
    recipient_row = _build_info_row(
        icon_url=recipient_icon_url,
        label="Получатель",
        value=recipient_name,
        trailing_text=recipient_trailing,
        theme=theme,
    )
    content_items.append(recipient_row)

    # Source card row
    source_trailing = f"·· {source_card_digits}" if source_card_digits else None
    source_row = _build_info_row(
        icon_url=source_card_icon_url,
        label="Списание с карты",
        value=source_card_name,
        trailing_text=source_trailing,
        theme=theme,
    )
    source_row_with_margin = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(),
        margins=dk.DivEdgeInsets(top=17),
        items=[source_row],
    )
    content_items.append(source_row_with_margin)

    # Amount row
    amount_row = _build_info_row(
        icon_url=wallet_icon_url,
        label="Сумма перевода",
        value=f"{amount} {currency}",
        theme=theme,
    )
    amount_row_with_margin = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(),
        margins=dk.DivEdgeInsets(top=17),
        items=[amount_row],
    )
    content_items.append(amount_row_with_margin)

    # Confirm button
    button_style = theme.typography.get_controls_2(bold=False)
    button = dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_horizontal=dk.DivContentAlignmentHorizontal.CENTER,
        content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
        width=dk.DivMatchParentSize(),
        height=dk.DivWrapContentSize(),
        border=dk.DivBorder(corner_radius=8),
        paddings=dk.DivEdgeInsets(
            left=16,
            right=16,
            top=10,
            bottom=10,
        ),
        background=[dk.DivSolidBackground(color=theme.colors.primary)],
        margins=dk.DivEdgeInsets(top=16),
        actions=[dk.DivAction(log_id="send_money_confirm", url=action_url)]
        if action_url
        else None,
        items=[
            dk.DivText(
                text=button_text,
                font_size=button_style.size,
                font_weight=dk.DivFontWeight("semibold"),
                text_color=theme.colors.text_on_primary,
                width=dk.DivWrapContentSize(),
                text_alignment_horizontal=dk.DivAlignmentHorizontal.CENTER,
            ),
        ],
    )
    content_items.append(button)

    # Build card container with shadow
    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(),
        border=dk.DivBorder(
            corner_radius=corner_radius,
            stroke=dk.DivStroke(color=theme.colors.grey_light, width=1),
            shadow=dk.DivShadow(
                color="#1A17360D",  # rgba(26, 23, 54, 0.05)
                offset=dk.DivPoint(x=dk.DivDimension(value=0), y=dk.DivDimension(value=4)),
                blur=12,
            ),
        ),
        background=[dk.DivSolidBackground(color=theme.colors.background)],
        paddings=dk.DivEdgeInsets(
            left=padding,
            right=padding,
            top=padding,
            bottom=padding,
        ),
        items=content_items,
    )


def send_money_widget_from_data(
    data: SendMoneyData,
    *,
    recipient_icon_url: str | None = None,
    source_card_icon_url: str | None = None,
    wallet_icon_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Create a send money widget from a data dictionary.

    Args:
        data: Send money data dictionary
        recipient_icon_url: URL to recipient avatar/icon
        source_card_icon_url: URL to card icon
        wallet_icon_url: URL to wallet icon
        theme: Theme tokens to use

    Returns:
        A send money widget
    """
    recipient = data.get("recipient", {})
    source_card = data.get("source_card", {})

    return send_money_widget(
        recipient_name=recipient.get("name", ""),
        source_card_name=source_card.get("card_name", ""),
        amount=data.get("amount", "0"),
        recipient_card_digits=recipient.get("card_last_digits"),
        source_card_digits=source_card.get("card_last_digits"),
        recipient_icon_url=recipient_icon_url or recipient.get("avatar_url"),
        source_card_icon_url=source_card_icon_url or source_card.get("card_icon_url"),
        wallet_icon_url=wallet_icon_url,
        currency=data.get("currency", "сум"),
        button_text=data.get("button_text", "Подтвердить перевод"),
        action_url=data.get("action_url"),
        theme=theme,
    )


def sample_send_money_widget(
    *,
    recipient_icon_url: str | None = None,
    source_card_icon_url: str | None = None,
    wallet_icon_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Create a sample send money widget with demo data.

    Useful for testing and previewing the component.

    Args:
        recipient_icon_url: URL to recipient avatar/icon
        source_card_icon_url: URL to card icon
        wallet_icon_url: URL to wallet icon
        theme: Theme tokens to use

    Returns:
        A sample send money widget
    """
    return send_money_widget(
        recipient_name="Alexander Guryanov",
        source_card_name="Зарплатная Smartbank",
        amount="200 000",
        recipient_card_digits="2221",
        source_card_digits="6847",
        recipient_icon_url=recipient_icon_url,
        source_card_icon_url=source_card_icon_url,
        wallet_icon_url=wallet_icon_url,
        currency="сум",
        button_text="Подтвердить перевод",
        action_url="smartbank://transfer/confirm",
        theme=theme,
    )
