from __future__ import annotations

from typing import TYPE_CHECKING, ClassVar

from textual.widgets import Tree

if TYPE_CHECKING:
    from smartwallet.model.category import Category

_CATEGORY_CLR = "#6366f1"
_INCOME_CLR = "#10b981"
_EXPENSE_CLR = "#ef4444"
_DIM = "#9ca3af"


def _amount_color(value: float) -> str:
    if value > 0:
        return _INCOME_CLR
    if value < 0:
        return _EXPENSE_CLR
    return _DIM


class BudgetTree(Tree["BudgetComponent"]):
    BORDER_TITLE: ClassVar[str] = "My Wallet"

    def __init__(self, root_category: Category) -> None:
        super().__init__("", data=root_category, id="budget-tree")
        self._root_category = root_category

    def on_mount(self) -> None:
        self.rebuild()

    def rebuild(self) -> None:
        self.clear()
        self.root.data = self._root_category
        self._update_root_label()
        self._build_children(self.root, self._root_category)
        self.root.expand()

    def _update_root_label(self) -> None:
        balance = self._root_category.get_balance()
        total = balance["total"]
        clr = _amount_color(total)
        self.root.set_label(
            f"[bold {_CATEGORY_CLR}]\u25c8 {self._root_category.name}[/]"
            f"  [{clr}]{total:+.2f}[/]"
        )

    def _build_children(
        self,
        parent_node: Tree.NodeType,
        category: Category,
    ) -> None:
        from smartwallet.model.category import Category as CategoryModel
        from smartwallet.model.transaction import Transaction as TransactionModel

        for child in category.children:
            if isinstance(child, CategoryModel):
                balance = child.get_balance()
                total = balance["total"]
                clr = _amount_color(total)
                label = (
                    f"[{_CATEGORY_CLR}]\u25b8 {child.name}[/]  [{clr}]{total:+.2f}[/]"
                )
                node = parent_node.add(label, data=child, expand=True)
                self._build_children(node, child)
            elif isinstance(child, TransactionModel):
                if child.amount >= 0:
                    sym, clr = "$", _INCOME_CLR
                else:
                    sym, clr = "\u2192", _EXPENSE_CLR
                label = f"[{clr}]{sym} {child.name}  {child.amount:+.2f}[/]"
                parent_node.add_leaf(label, data=child)

    @property
    def root_category(self) -> Category:
        return self._root_category

    @root_category.setter
    def root_category(self, value: Category) -> None:
        self._root_category = value
        self.rebuild()
