# Bankr Dashboards: Income & Expenses

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 bar plot
def refresh_panel(book: pd.DataFrame, first_year: str, years: str):
    # Decide on period to use
    period = "m"
    if int(years) == 2 or int(years) == 3:
        period = "q"
    if int(years) == 4:
        period = "t"
    if int(years) == 5:
        period = "f"
    # Calculate amounts from the Book
    amounts = bc.sum_per_cat_period(book, int(first_year), int(years), period=period, pivot=True)
    amounts = amounts.drop(labels="internal", axis=1)
    # I18N for cats in amounts
    cols = list(amounts)
    pnames = {}
    for col in cols:
        pnames[col] = i18n.t("cats." + col)
    amounts.rename(mapper=pnames, axis="columns", inplace=True)
    # Plot bars
    return amounts.hvplot.bar(
        stacked=True,
        width=1200,
        height=750,
        title=i18n.t("app.balance"),
        xlabel=i18n.t("general.period"),
        ylabel=i18n.t("general.amount"),
    )


# Panel Bind: Refresh the transaction statistics
def refresh_table(book: pd.DataFrame, first_year: str, years: str):
    # Decide on period to use
    period = "m"
    if int(years) == 2 or int(years) == 3:
        period = "q"
    if int(years) == 4:
        period = "t"
    if int(years) == 5:
        period = "f"
    # Calculate amounts from the Book
    amounts = bc.sum_per_cat_period(book, int(first_year), int(years), period=period, pivot=True)
    amounts = amounts.drop(labels="internal", axis=1)
    amounts = bc.append_totals(amounts)
    # I18N for cats in amounts
    cols = list(amounts)
    pnames = {}
    for col in cols:
        pnames[col] = i18n.t("cats." + col)
    amounts.rename(mapper=pnames, axis="columns", inplace=True)
    amounts.rename(index={"total": i18n.t("general.total")}, inplace=True)
    # Table
    balance = pn.pane.DataFrame(amounts, index_names=False)
    return pn.Column("### " + i18n.t("app.balance"), balance)


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

# Widgets & Pane select
first_year = pn.widgets.Select(name=i18n.t("app.first_year"), options=bc.list_years_with_tracts(book))
years = pn.widgets.Select(name=i18n.t("app.years"), options=["1", "2", "3", "4", "5"])
select = pn.Row("### " + i18n.t("app.select_period"), first_year, years, styles=dict(background="Whitesmoke"))

# Pane tabs
plot = pn.bind(refresh_panel, book=book, first_year=first_year, years=years)
table = pn.bind(refresh_table, book=book, first_year=first_year, years=years)
tabs = pn.Tabs((i18n.t("app.plot"), plot), (i18n.t("app.table"), table), dynamic=True)

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