from typing import Optional

from django.dispatch import receiver
from rest_framework.reverse import reverse
from wbcore.contrib.color.enums import WBColor
from wbcore.enums import Unit
from wbcore.metadata.configs import display as dp
from wbcore.metadata.configs.display import Page, Style, add_display_pages
from wbcore.metadata.configs.display.instance_display.layouts.layouts import Layout
from wbcore.metadata.configs.display.instance_display.shortcuts import (
    Display,
    create_simple_display,
    create_simple_section,
    default,
)
from wbcore.metadata.configs.display.view_config import DisplayViewConfig
from wbcrm.viewsets.display import AccountDisplayConfig

from wbcommission.models import CommissionType


class CommissionTypeDisplayConfigClass(DisplayViewConfig):
    def get_list_display(self) -> Optional[dp.ListDisplay]:
        return dp.ListDisplay(
            fields=[
                dp.Field(key="name", label="Name"),
                dp.Field(key="key", label="Key"),
            ]
        )

    def get_instance_display(self) -> Display:
        return create_simple_display([["name", "key"]])


class CommissionDisplayConfig(DisplayViewConfig):
    def get_list_display(self) -> Optional[dp.ListDisplay]:
        return dp.ListDisplay(
            legends=[
                dp.Legend(
                    items=[
                        dp.LegendItem(
                            icon=WBColor.BLUE.value,
                            label="Simulated percent",
                        ),
                    ],
                ),
            ],
            fields=[
                dp.Field(key="order", label="Order", width=Unit.PIXEL(75)),
                dp.Field(
                    key=None,
                    label="Recipient",
                    open_by_default=False,
                    children=[
                        dp.Field(key="recipient_repr", label="Group", width=Unit.PIXEL(250)),
                        dp.Field(
                            key="recipient_details", label="Simulated Details", width=Unit.PIXEL(250), show="open"
                        ),
                    ],
                ),
                dp.Field(
                    key=None,
                    label="Rules",
                    open_by_default=True,
                    children=[
                        dp.Field(
                            key="percent",
                            label="Percent",
                            width=Unit.PIXEL(100),
                            formatting_rules=[
                                dp.FormattingRule(
                                    condition=[("∃", True, "recipient_repr")],
                                    style={"color": WBColor.BLUE.value, "fontWeight": "bold"},
                                )
                            ],
                        ),
                        dp.Field(key="net_commission", label="Net", width=Unit.PIXEL(100)),
                        dp.Field(key="timespan", label="Timespan", show="open", width=Unit.PIXEL(300)),
                        dp.Field(
                            key="assets_under_management_range", label="AUM range", show="open", width=Unit.PIXEL(300)
                        ),
                    ],
                ),
                dp.Field(
                    key=None,
                    label="Permission",
                    open_by_default=False,
                    children=[
                        dp.Field(key="is_hidden", label="Hidden", width=Unit.PIXEL(100)),
                        dp.Field(key="roles_repr", label="Direct Roles", width=Unit.PIXEL(350), show="open"),
                    ],
                ),
                dp.Field(key="exclusion_rule_account_role_type", label="Exclusion rule type"),
            ],
            tree=True,
            tree_group_field="order",
            tree_group_field_sortable=False,
            tree_group_level_options=[
                dp.TreeGroupLevelOption(
                    filter_key="commission",
                    filter_depth=1,
                    list_endpoint=reverse(
                        "wbcommission:commissionrule-list",
                        args=[],
                        request=self.request,
                    ),
                )
            ],
        )

    def get_instance_display(self) -> Display | None:
        return create_simple_display(
            [
                ["crm_recipient", "portfolio_role_recipient", "account_role_type_recipient"],
                ["net_commission", "is_hidden", "exclusion_rule_account_role_type"],
                ["rule_section", "rule_section", "rule_section"],
            ],
            sections=[
                create_simple_section(
                    "rule_section",
                    "Validity",
                    [["rules"]],
                    "rules",
                    collapsed=False,
                )
            ],
        )


class CommissionRuleCommissionDisplayConfig(DisplayViewConfig):
    def get_list_display(self) -> Optional[dp.ListDisplay]:
        return dp.ListDisplay(
            fields=[
                dp.Field(key="percent", label="Percent"),
                dp.Field(key="net_commission", label="Net"),
                dp.Field(key="timespan", label="Timespan"),
                dp.Field(key="assets_under_management_range", label="AUM range"),
            ]
        )

    def get_instance_display(self) -> Display | None:
        return create_simple_display(
            [
                ["percent", "consider_zero_percent_for_exclusion"],
                ["timespan", "assets_under_management_range"],
            ]
        )


@receiver(add_display_pages, sender=AccountDisplayConfig)
def add_commission_page(sender, *args, **kwargs):
    grid_template_areas = []
    sections = []
    grid_template_rows = []
    ct_count = CommissionType.objects.count()
    for ct in CommissionType.objects.all():
        key = "commission-" + ct.key
        grid_template_areas.append([key])
        sections.append(
            create_simple_section(
                key=key,
                title=ct.name,
                grid_template_areas=[[key]],
                inline_key=key,
                collapsible=False,
            )
        )
        grid_template_rows.append(Style.pct(int(100 / ct_count)))
    return [
        Page(
            title="Commission",
            layouts={
                default(): Layout(
                    grid_auto_rows=Style.AUTO,
                    grid_template_areas=grid_template_areas,
                    grid_template_rows=grid_template_rows,
                    sections=sections,
                )
            },
        ),
    ]
