"""Home balance widget block aligned with Smartbank Figma design system.

Provides the "Мой дом" (My Home) widget for displaying utility balances
like electricity, gas, water, and recycling.

Figma reference: node-id=46522:164882 (myhome)
"""

from __future__ import annotations

from typing import TypedDict, Literal

import pydivkit as dk

from smarty_ui.tokens.theme import Theme, default_theme

UtilityType = Literal["electricity", "gas", "water", "recycling", "other"]


class UtilityBalanceData(TypedDict, total=False):
    """Data structure for a utility balance item."""

    utility_type: UtilityType
    icon_url: str | None
    balance: str
    currency: str
    is_negative: bool
    action_url: str | None


class HomeBalanceData(TypedDict, total=False):
    """Data structure for the home balance widget."""

    title: str
    subtitle: str
    house_image_url: str | None
    utilities: list[UtilityBalanceData]
    action_url: str | None


# Default utility icons (from Figma assets)
DEFAULT_UTILITY_ICONS = {
    "electricity": "https://www.figma.com/api/mcp/asset/f5c66deb-495d-4a04-822b-80c3d6c2eacd",  # lamp
    "gas": "https://www.figma.com/api/mcp/asset/a25fda31-5c14-4b92-86f3-ec4a00a77863",  # fire
    "recycling": "https://www.figma.com/api/mcp/asset/2c22ace0-b9f7-4716-896b-ce1b09dee575",  # recycle
    "water": "https://www.figma.com/api/mcp/asset/82ccf239-fbf8-4e31-a797-916197ab5001",  # drop
}

# Default house image
DEFAULT_HOUSE_IMAGE = (
    "https://www.figma.com/api/mcp/asset/8494ceb3-06e9-4c63-932e-8f44a2073759"
)


def _build_utility_balance_item(
    balance: str,
    *,
    utility_type: UtilityType = "other",
    icon_url: str | None = None,
    currency: str = "сум",
    is_negative: bool = False,
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Build a single utility balance row.

    Design specs (from Figma):
    - Icon: 24x24 in 24x24 grey-light (#F9F9F9) circular container
    - Balance: Controls 02 SemiBold 14px, black (#1A1736)
    - Currency: Controls 02 SemiBold 14px, black (#1A1736)
    - Gap between icon and text: 8px
    """
    # Get icon URL (use default if not provided)
    icon = icon_url or DEFAULT_UTILITY_ICONS.get(utility_type)

    # Typography: Controls 02 SemiBold 14px
    controls_style = theme.typography.get_controls_2(bold=False)

    items: list[dk.Div] = []

    # Icon container (24x24 with grey-light background)
    if icon:
        icon_container = dk.DivContainer(
            orientation=dk.DivContainerOrientation.HORIZONTAL,
            content_alignment_horizontal=dk.DivContentAlignmentHorizontal.CENTER,
            content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
            width=dk.DivFixedSize(value=24),
            height=dk.DivFixedSize(value=24),
            border=dk.DivBorder(corner_radius=16),
            background=[dk.DivSolidBackground(color=theme.colors.grey_light)],
            items=[
                dk.DivImage(
                    image_url=icon,
                    width=dk.DivFixedSize(value=16),
                    height=dk.DivFixedSize(value=16),
                    scale=dk.DivImageScale.FIT,
                )
            ],
        )
        items.append(icon_container)

    # Format balance with negative sign if needed
    balance_text = f"- {balance}" if is_negative else balance

    # Balance + currency text
    amount_container = dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
        width=dk.DivWrapContentSize(),
        margins=dk.DivEdgeInsets(left=8) if icon else None,
        items=[
            dk.DivText(
                text=balance_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(),
            ),
            dk.DivText(
                text=f" {currency}",
                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(),
            ),
        ],
    )
    items.append(amount_container)

    # Build row container
    row_kwargs: dict = {
        "orientation": dk.DivContainerOrientation.HORIZONTAL,
        "content_alignment_vertical": dk.DivAlignmentVertical.CENTER,
        "width": dk.DivMatchParentSize(),
        "items": items,
    }

    if action_url:
        row_kwargs["actions"] = [
            dk.DivAction(log_id=f"utility_{utility_type}", url=action_url)
        ]

    return dk.DivContainer(**row_kwargs)


def _build_divider(theme: Theme = default_theme) -> dk.DivSeparator:
    """Build a horizontal divider line."""
    return dk.DivSeparator(
        delimiter_style=dk.DivSeparatorDelimiterStyle(
            color=theme.colors.grey_medium,
        ),
        margins=dk.DivEdgeInsets(top=8, bottom=8),
    )


def home_balance_widget(
    title: str = "Мой дом",
    subtitle: str = "Балансы",
    *,
    utilities: list[UtilityBalanceData] | None = None,
    house_image_url: str | None = None,
    corner_radius: int = 20,
    action_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Home balance widget showing utility balances.

    A white card with:
    - House illustration (bottom left, rotated)
    - Title and subtitle (top left)
    - Utility balance rows (right side) with icons and amounts

    Design specs (from Figma):
    - Background: white
    - Corner radius: 20px
    - Padding: 16px horizontal, 12px vertical
    - Gap between sections: 64px
    - House image: 120x86, positioned bottom-left, rotated 180°
    - Balance column: 150px width

    Args:
        title: Widget title (e.g., "Chilonzor 7, 35, Muqimiy ko'chasi")
        subtitle: Widget subtitle (e.g., "Балансы")
        utilities: List of utility balance data
        house_image_url: URL to house illustration
        corner_radius: Border radius (default 20)
        action_url: Optional URL to navigate on tap
        theme: Theme tokens to use

    Returns:
        A DivContainer representing the home balance widget
    """
    # Typography styles
    controls_style = theme.typography.get_controls_2(bold=True)  # Bold 14px for title
    text_style = theme.typography.get_text_2()  # Medium 12px for subtitle

    # Use default house image if not provided
    house_image = house_image_url or DEFAULT_HOUSE_IMAGE

    # Build utility balance items
    balance_items: list[dk.Div] = []
    if utilities:
        for i, utility in enumerate(utilities):
            # Add divider between items (not before first)
            if i > 0:
                balance_items.append(_build_divider(theme))

            item = _build_utility_balance_item(
                balance=utility.get("balance", "0"),
                utility_type=utility.get("utility_type", "other"),
                icon_url=utility.get("icon_url"),
                currency=utility.get("currency", "сум"),
                is_negative=utility.get("is_negative", False),
                action_url=utility.get("action_url"),
                theme=theme,
            )
            balance_items.append(item)

    # Build content layers
    layers: list[dk.Div] = []

    # Layer 1: House image (bottom-left, positioned absolutely)
    if house_image:
        house_container = dk.DivImage(
            image_url=house_image,
            width=dk.DivFixedSize(value=114),  # 95% of 120
            height=dk.DivFixedSize(value=77),  # ~89% of 86
            scale=dk.DivImageScale.FIT,
            alignment_horizontal=dk.DivAlignmentHorizontal.LEFT,
            alignment_vertical=dk.DivAlignmentVertical.BOTTOM,
        )
        layers.append(house_container)

    # Layer 2: Main content (title + balances)
    # Title section
    title_section = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(weight=1),
        items=[
            dk.DivText(
                text=title,
                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.DivMatchParentSize(),
                max_lines=1,
            ),
            dk.DivText(
                text=subtitle,
                font_size=text_style.size,
                font_weight=dk.DivFontWeight(text_style.weight),
                text_color=theme.colors.text_secondary,
                line_height=text_style.line_height,
                width=dk.DivMatchParentSize(),
            ),
        ],
    )

    # Balance section
    balance_section = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        content_alignment_horizontal=dk.DivContentAlignmentHorizontal.LEFT,
        width=dk.DivFixedSize(value=150),
        items=balance_items,
    )

    # Main content row
    content_row = dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        content_alignment_vertical=dk.DivAlignmentVertical.TOP,
        width=dk.DivMatchParentSize(),
        items=[title_section, balance_section],
    )
    layers.append(content_row)

    # Build action if URL provided
    actions = None
    if action_url:
        actions = [dk.DivAction(log_id="home_balance_widget", url=action_url)]

    # Build main container

    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivMatchParentSize(),
        height=dk.DivWrapContentSize(),
        border=dk.DivBorder(corner_radius=corner_radius),
        background=[dk.DivSolidBackground(color=theme.colors.background)],
        paddings=dk.DivEdgeInsets(
            left=20,
            right=20,
            top=20,
            bottom=20,
        ),
        actions=actions,
        items=[
            dk.DivContainer(
                orientation=dk.DivContainerOrientation.OVERLAP,
                width=dk.DivMatchParentSize(),
                height=dk.DivWrapContentSize(),
                items=layers,
            )
        ],
    )


def home_balance_widget_from_data(
    data: HomeBalanceData,
    *,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Create a home balance widget from a data dictionary.

    Args:
        data: Home balance data dictionary
        theme: Theme tokens to use

    Returns:
        A home balance widget
    """
    return home_balance_widget(
        title=data.get("title", "Мой дом"),
        subtitle=data.get("subtitle", "Балансы"),
        utilities=data.get("utilities"),
        house_image_url=data.get("house_image_url"),
        action_url=data.get("action_url"),
        theme=theme,
    )


# Convenience function with sample data
def sample_home_balance_widget(
    *,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """Create a sample home balance widget with default utility data.

    Useful for testing and demonstration purposes.

    Args:
        theme: Theme tokens to use

    Returns:
        A home balance widget with sample data
    """
    sample_utilities: list[UtilityBalanceData] = [
        {
            "utility_type": "electricity",
            "balance": "1 241 200",
            "currency": "UZS",
            "is_negative": True,
        },
        {
            "utility_type": "gas",
            "balance": "10 000 200",
            "currency": "UZS",
            "is_negative": True,
        },
        {
            "utility_type": "recycling",
            "balance": "31 800",
            "currency": "UZS",
            "is_negative": False,
        },
        {
            "utility_type": "water",
            "balance": "25 000",
            "currency": "UZS",
            "is_negative": False,
        },
    ]

    return home_balance_widget(
        title="Chilonzor 7, 35, Muqimiy ko'chasi",
        subtitle="Балансы",
        utilities=sample_utilities,
        theme=theme,
    )
