"""Home card blocks aligned with Smartbank Figma design system.

Provides "My Home" card components for displaying smart home information
with house illustrations and pagination indicators.
"""

from __future__ import annotations

from typing import Literal

import pydivkit as dk

from smarty_ui.tokens.theme import Theme, default_theme

HomeCardType = Literal["large", "big", "medium", "small", "empty"]


# Default house illustration URLs (from Figma assets)
# These should be replaced with actual asset URLs in production
DEFAULT_HOUSE_IMAGES = {
    "large": "https://www.figma.com/api/mcp/asset/a4133c14-7855-4444-9b4b-b4c3759f088f",
    "big": "https://www.figma.com/api/mcp/asset/7a030b8c-86b5-4902-9ea0-8d7a151baad8",
    "medium": "https://www.figma.com/api/mcp/asset/fef9e7e4-dc89-4cc9-aa90-770d3f122cd6",
    "small": "https://www.figma.com/api/mcp/asset/3e21e41f-0462-464e-b43e-413a903d4884",
    "empty": "https://www.figma.com/api/mcp/asset/b07c4372-903b-487b-bd79-a33c8494dbac",
}


def _create_pagination_dots(
    total: int,
    active: int,
    *,
    active_color: str,
    inactive_color: str,
    dot_size: int = 6,
    spacing: int = 5,
) -> dk.DivContainer:
    """Create pagination indicator dots.

    Args:
        total: Total number of dots
        active: Index of active dot (0-based)
        active_color: Color for active dot
        inactive_color: Color for inactive dots
        dot_size: Size of each dot in dp
        spacing: Spacing between dots in dp

    Returns:
        A DivContainer with pagination dots
    """
    dots: list[dk.Div] = []

    for i in range(total):
        is_active = i == active
        dot = dk.DivContainer(
            width=dk.DivFixedSize(value=dot_size),
            height=dk.DivFixedSize(value=dot_size),
            border=dk.DivBorder(corner_radius=dot_size // 2),
            background=[
                dk.DivSolidBackground(
                    color=active_color if is_active else inactive_color
                )
            ],
            margins=dk.DivEdgeInsets(right=spacing) if i < total - 1 else None,
        )
        dots.append(dot)

    return dk.DivContainer(
        orientation=dk.DivContainerOrientation.HORIZONTAL,
        width=dk.DivWrapContentSize(),
        height=dk.DivWrapContentSize(),
        items=dots,
    )


def home_card(
    name: str = "Название дома",
    *,
    card_type: HomeCardType = "large",
    house_image_url: str | None = None,
    total_pages: int = 4,
    current_page: int = 0,
    action_url: str | None = None,
    add_new_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivContainer:
    """My Home card component matching Smartbank Figma design.

    Displays a smart home card with:
    - "Мой дом" label
    - House name
    - House illustration
    - Pagination dots (for multiple homes)

    Args:
        name: Name of the home (e.g., "Название дома")
        card_type: Card variant - "large", "big", "medium", "small", or "empty"
        house_image_url: URL to house illustration image
        total_pages: Total number of pagination dots
        current_page: Current active page (0-based index)
        action_url: URL to navigate on card tap
        add_new_url: URL for "Add new" action (only for empty type)
        theme: Theme tokens to use

    Returns:
        A DivContainer representing the home card
    """
    # Card dimensions
    width = 343
    height = 110
    corner_radius = theme.spacing.radius_lg  # 18

    # Get typography styles
    caption_style = theme.typography.get_caption_1()  # SemiBold 12px
    controls_style = theme.typography.get_controls_1(bold=True)  # Bold 16px

    # Use default house image if not provided
    image_url = house_image_url or DEFAULT_HOUSE_IMAGES.get(card_type)

    # Colors from Figma
    text_black = theme.colors.text_primary  # #1A1736
    text_blue = theme.colors.primary  # #076AE2
    dot_active = text_black
    dot_inactive = theme.colors.grey_medium  # #E6E7E8

    # Build card items
    items: list[dk.Div] = []

    # White background box with shadow
    # Note: DivKit shadow is applied via border or background
    # We'll use a container with white background
    bg_container = dk.DivContainer(
        width=dk.DivMatchParentSize(),
        height=dk.DivMatchParentSize(),
        border=dk.DivBorder(corner_radius=corner_radius),
        background=[dk.DivSolidBackground(color=theme.colors.background)],
    )
    items.append(bg_container)

    # Content container (text on left side)
    content_items: list[dk.Div] = []

    # "Мой дом" label
    content_items.append(
        dk.DivText(
            text="Мой дом",
            font_size=caption_style.size,
            font_weight=dk.DivFontWeight(caption_style.weight),
            text_color=text_black,
            line_height=caption_style.line_height,
            width=dk.DivWrapContentSize(),
        )
    )

    # House name or "Add new" text
    if card_type == "empty":
        # "Добавить новый" with blue color and arrow
        add_new_row = dk.DivContainer(
            orientation=dk.DivContainerOrientation.HORIZONTAL,
            content_alignment_vertical=dk.DivAlignmentVertical.CENTER,
            width=dk.DivWrapContentSize(),
            items=[
                dk.DivText(
                    text="Добавить новый",
                    font_size=controls_style.size,
                    font_weight=dk.DivFontWeight(controls_style.weight),
                    text_color=text_blue,
                    line_height=controls_style.line_height,
                    width=dk.DivWrapContentSize(),
                ),
                dk.DivText(
                    text=" ›",
                    font_size=controls_style.size,
                    font_weight=dk.DivFontWeight(controls_style.weight),
                    text_color=text_blue,
                    line_height=controls_style.line_height,
                    width=dk.DivWrapContentSize(),
                ),
            ],
            margins=dk.DivEdgeInsets(top=24),
        )
        content_items.append(add_new_row)
    else:
        # House name
        content_items.append(
            dk.DivText(
                text=name,
                font_size=controls_style.size,
                font_weight=dk.DivFontWeight(controls_style.weight),
                text_color=text_black,
                line_height=controls_style.line_height,
                width=dk.DivWrapContentSize(),
                margins=dk.DivEdgeInsets(top=4),
            )
        )

        # Pagination dots (not for empty type)
        pagination = _create_pagination_dots(
            total=total_pages,
            active=current_page,
            active_color=dot_active,
            inactive_color=dot_inactive,
        )
        content_items.append(
            dk.DivContainer(
                width=dk.DivWrapContentSize(),
                height=dk.DivWrapContentSize(),
                margins=dk.DivEdgeInsets(top=18),
                items=[pagination],
            )
        )

    # Text content container (positioned on left)
    text_container = dk.DivContainer(
        orientation=dk.DivContainerOrientation.VERTICAL,
        width=dk.DivWrapContentSize(),
        height=dk.DivWrapContentSize(),
        alignment_horizontal=dk.DivAlignmentHorizontal.LEFT,
        alignment_vertical=dk.DivAlignmentVertical.TOP,
        paddings=dk.DivEdgeInsets(left=20, top=20),
        items=content_items,
    )
    items.append(text_container)

    # House illustration (positioned on right)
    if image_url:
        # Image container positioned on the right side
        image_container = dk.DivImage(
            image_url=image_url,
            width=dk.DivFixedSize(value=110),
            height=dk.DivFixedSize(value=110),
            scale=dk.DivImageScale.FIT,
            alignment_horizontal=dk.DivAlignmentHorizontal.RIGHT,
            alignment_vertical=dk.DivAlignmentVertical.CENTER,
        )
        items.append(image_container)

    # Build card container
    card_kwargs: dict = {
        "orientation": dk.DivContainerOrientation.OVERLAP,
        "width": dk.DivFixedSize(value=width),
        "height": dk.DivFixedSize(value=height),
        "border": dk.DivBorder(corner_radius=corner_radius),
        "items": items,
    }

    # Add action based on card type
    if card_type == "empty" and add_new_url:
        card_kwargs["actions"] = [
            dk.DivAction(log_id="home_card_add_new", url=add_new_url)
        ]
    elif action_url:
        card_kwargs["actions"] = [dk.DivAction(log_id="home_card_tap", url=action_url)]

    return dk.DivContainer(**card_kwargs)


def home_card_carousel(
    homes: list[dict],
    *,
    empty_card_url: str | None = None,
    theme: Theme = default_theme,
) -> dk.DivGallery:
    """Carousel of home cards with optional "Add new" card at the end.

    Args:
        homes: List of home data dicts with keys:
            - name: Home name
            - image_url: Optional house illustration URL
            - action_url: Optional tap action URL
        empty_card_url: URL for "Add new" card action
        theme: Theme tokens to use

    Returns:
        A DivGallery containing home cards
    """
    cards: list[dk.Div] = []
    total = len(homes)

    # Create cards for each home
    for i, home_data in enumerate(homes):
        # Determine card type based on position or data
        card_type: HomeCardType = "large"
        if "type" in home_data:
            card_type = home_data["type"]

        card = home_card(
            name=home_data.get("name", "Название дома"),
            card_type=card_type,
            house_image_url=home_data.get("image_url"),
            total_pages=total + (1 if empty_card_url else 0),
            current_page=i,
            action_url=home_data.get("action_url"),
            theme=theme,
        )
        cards.append(card)

    # Add "Add new" card at the end
    if empty_card_url:
        empty_card = home_card(
            card_type="empty",
            total_pages=total + 1,
            current_page=total,
            add_new_url=empty_card_url,
            theme=theme,
        )
        cards.append(empty_card)

    return dk.DivGallery(
        items=cards,
        orientation=dk.DivGalleryOrientation.HORIZONTAL,
        item_spacing=12,
        width=dk.DivMatchParentSize(),
        height=dk.DivWrapContentSize(),
    )
