# Bankr Dashbords: Accounts

from pathlib import Path
import i18n

import panel as pn
import pandas as pd
# import hvplot.pandas  # noqa

from bankr import calc as bc
from bankr import files as bf

# Panel init
pn.extension(design="material")

# Bankr Data Import
config_path = Path("./bankr.yaml").resolve()
params = bf.read_bankr_yaml(config_path)
data_path = Path(params["DATA_PATH"]).resolve()
accounts = bf.read_bankr_yaml(data_path / "accounts.yaml")
book = bf.unpickle_book(data_path)

# I18N
bankr_path = Path(__file__).parent.parent.resolve()
i18n.set("locale", params["LOCALE"])
i18n.set("fallback", "en")
i18n.load_path.append(bankr_path / "locale")


# Panel Bind: Refresh the table Accounts
def refresh_accounts(
    book: pd.DataFrame,
    accounts: list[dict],
    active: bool,
    types: list[str],
    owners: list[str],
    groups: list[str],
):
    # Create table of accounts and select data
    accounts = pd.DataFrame(bc.calc_book_stats(book, accounts))
    if active:
        accounts = accounts[accounts["active"] == "True"]
        accounts = accounts.drop(columns="active")
    accounts = accounts[accounts["type"].isin(types)]
    accounts = accounts[accounts["group"].isin(groups)]
    accounts = accounts[accounts["owner"].isin(owners)]
    # Calculate totals
    accounts_sum = f"## Gesamtbetrag: {accounts['balance'].sum()}\n### {accounts['tracts'].sum()} Transaktionen"
    accounts_pane = pn.pane.DataFrame(accounts, justify="left")
    accounts_sum_pane = pn.pane.Markdown(accounts_sum)
    return pn.Row(accounts_pane, accounts_sum_pane)


# Sidebar
sb_md = f"{i18n.t('app.accounts')}\n\n[{i18n.t('app.balance')}](/balance)"
sb_md += f"\n\nInfo: {__name__}"  # For test purposes only, in this case bokeh_app_0020c62d15a341fa80871f12b9adc73d
sidebar = pn.pane.Markdown(sb_md)

# Widgets for row select
# Hint: dict.fromkeys([l])) preserves order and removes duplicates
account_types = list(dict.fromkeys([account["type"] for account in accounts if "type" in account]))
account_groups = list(dict.fromkeys([account["group"] for account in accounts if "group" in account]))
account_owners = list(dict.fromkeys([account["owner"] for account in accounts if "owner" in account]))
active = pn.widgets.Checkbox(name=i18n.t("app.active_only"), value=True)
types = pn.widgets.CheckBoxGroup(name="types", options=account_types, value=account_types)
owners = pn.widgets.CheckBoxGroup(name="owners", options=account_owners, value=account_owners)
groups = pn.widgets.CheckBoxGroup(name="groups", options=account_groups, value=account_groups)
select = pn.Row("### " + i18n.t("app.accounts"), active, types, owners, groups, styles=dict(background="Whitesmoke"))

# Row table
table = pn.bind(
    refresh_accounts,
    book=book,
    accounts=accounts,
    active=active,
    types=types,
    owners=owners,
    groups=groups,
)

# Panel Definition
pn.template.FastListTemplate(
    site="Bankr",
    title="Dashboards",
    sidebar=sidebar,
    main=[select, table],
).servable()
