from decimal import Decimal
from typing import Optional

from rio import Column, Component, event, Text, TextStyle, Button, Color, Revealer, Row, ProgressCircle, Link, Image

from src.ezgg_lan_manager import ConfigurationService, UserService, AccountingService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.types.Transaction import Transaction
from src.ezgg_lan_manager.types.User import User
from src.ezgg_lan_manager.types.UserSession import UserSession


class AccountPage(Component):
    user: Optional[User] = None
    balance: Optional[Decimal] = None
    transaction_history: list[Transaction] = list()
    payment_qr_image: bytes = None
    banking_info_revealer_open: bool = False
    paypal_info_revealer_open: bool = False

    @event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Guthabenkonto")
        try:
            user_id = self.session[UserSession].user_id
        except KeyError:
            pass
        else:
            self.user = await self.session[UserService].get_user(user_id)
            self.balance = await self.session[AccountingService].get_balance(user_id)
            self.transaction_history = await self.session[AccountingService].get_transaction_history(user_id)
            self.payment_qr_image = self.session[AccountingService].make_payment_qr_image(
                    "Einfach Zocken Gaming Gesellschaft",
                    "GENODE51BIK",
                    "DE47517624340019856607",
                    f"AUFLADUNG - {self.user.user_id} - {self.user.user_name}")

    async def _on_banking_info_press(self) -> None:
        self.banking_info_revealer_open = not self.banking_info_revealer_open

    async def _on_paypal_info_press(self) -> None:
        self.paypal_info_revealer_open = not self.paypal_info_revealer_open

    def build(self) -> Component:
        if not self.user or not self.payment_qr_image:
            return Column(
                MainViewContentBox(
                    ProgressCircle(
                        color="secondary",
                        align_x=0.5,
                        margin_top=2,
                        margin_bottom=2
                    )
                ),
                align_y=0,
            )

        banking_info_revealer = Revealer(
            is_open=self.bind().banking_info_revealer_open,
            header=None,
            content=Column(
                Text(
                    "Bankverbindung:",
                    style=TextStyle(
                        fill=self.session.theme.background_color
                    ),
                    margin=0,
                    margin_top=0,
                    margin_bottom=1,
                    align_x=0.5
                ),
                Text(
                    "Kontoinhaber:     Einfach Zocken Gaming Gesellschaft\n"
                    "IBAN:             DE47 5176 2434 0019 8566 07\n"
                    "BLZ:              51762434\n"
                    "BIC:              GENODE51BIK\n\n"
                    "Verwendungszweck:",
                    style=TextStyle(
                        fill=self.session.theme.background_color,
                        font_size=0.7
                    ),
                    margin=0,
                    margin_bottom=1,
                    align_x=0.2
                ),
                Text(
                    f"AUFLADUNG - {self.user.user_id} - {self.user.user_name}",
                    style=TextStyle(
                        fill=self.session.theme.neutral_color
                    ),
                    margin=0,
                    margin_bottom=1,
                    align_x=0.5
                ),
                Image(self.payment_qr_image,
                      min_width=20,
                      min_height=20
                )
            ),
            margin=2,
            margin_top=0,
            margin_bottom=1,
            grow_x=True
        )

        paypal_info_revealer = Revealer(
            is_open=self.bind().paypal_info_revealer_open,
            header=None,
            content=Column(
                Text(
                    "PayPal Verbindung:",
                    style=TextStyle(
                        fill=self.session.theme.background_color
                    ),
                    margin=0,
                    margin_top=0,
                    margin_bottom=1,
                    align_x=0.5
                ),
                Text(
                    "Empfänger:        tech@ezgg-ev.de\n"
                    "Zahlungsart:      Freunde und Familie\n"
                    "Verwendungszweck:",
                    style=TextStyle(
                        fill=self.session.theme.background_color,
                        font_size=0.7
                    ),
                    margin=0,
                    margin_bottom=1,
                    align_x=0.2
                ),
                Text(
                    f"AUFLADUNG - {self.user.user_id} - {self.user.user_name}",
                    style=TextStyle(
                        fill=self.session.theme.neutral_color
                    ),
                    margin=0,
                    margin_bottom=1,
                    align_x=0.5
                )
            ),
            margin=2,
            margin_top=0,
            margin_bottom=1,
            grow_x=True
        )

        transaction_history = Column(
            Text(
                "Transaktionshistorie",
                style=TextStyle(
                    fill=self.session.theme.background_color,
                    font_size=1.2
                ),
                margin_top=1,
                margin_bottom=1,
                align_x=0.5
            )
        )

        for transaction in sorted(self.transaction_history, key=lambda t: t.transaction_date, reverse=True):
            transaction_history.add(
                Row(
                    Text(
                        f"{transaction.reference} ({transaction.transaction_date.strftime('%d.%m - %H:%M')})",
                        style=TextStyle(
                            fill=self.session.theme.danger_color if transaction.is_debit else self.session.theme.success_color,
                            font_size=0.8
                        ),
                        margin=0,
                        margin_top=0,
                        margin_left=0.5,
                        margin_bottom=0.4,
                        align_x=0
                    ),
                    Text(
                        f"{'-' if transaction.is_debit else '+'}{AccountingService.make_euro_string_from_decimal(transaction.value)}",
                        style=TextStyle(
                            fill=self.session.theme.danger_color if transaction.is_debit else self.session.theme.success_color,
                            font_size=0.8
                        ),
                        margin=0,
                        margin_top=0,
                        margin_right=0.5,
                        margin_bottom=0.4,
                        align_x=1
                    )
                )
            )
        return Column(
            MainViewContentBox(
                content=Text(
                    f"Kontostand: {AccountingService.make_euro_string_from_decimal(self.balance)}",
                    style=TextStyle(
                        fill=self.session.theme.background_color,
                        font_size=1.2
                    ),
                    margin=2,
                    align_x=0.5
                )
            ),
            MainViewContentBox(
                content=Column(
                    Text(
                        "LAN-Konto aufladen",
                        style=TextStyle(
                            fill=self.session.theme.background_color,
                            font_size=1.2
                        ),
                        margin=2,
                        align_x=0.5
                    ),
                    Button(
                        content=Text("BANKÜBERWEISUNG", style=TextStyle(fill=Color.from_hex("121212"), font_size=0.8), justify="center"),
                        shape="rectangle",
                        style="major",
                        color="secondary",
                        grow_x=True,
                        margin=2,
                        margin_top=0,
                        margin_bottom=1,
                        on_press=self._on_banking_info_press
                    ),
                    banking_info_revealer,
                    Button(
                        content=Text("PAYPAL (ohne Gebühr - Freunde&Familie)", style=TextStyle(fill=Color.from_hex("121212"), font_size=0.8), justify="center"),
                        shape="rectangle",
                        style="major",
                        color="secondary",
                        grow_x=True,
                        margin=2,
                        margin_top=0,
                        on_press=self._on_paypal_info_press
                    ),
                    paypal_info_revealer,
                    # Disabled because people did not understand the fee's and kept charging 24.03 € to their accounts
                    # Link(
                    #     content=Button(
                    #         content=Text("PAYPAL (3% Gebühr - Gewerblich)", style=TextStyle(fill=Color.from_hex("121212"), font_size=0.8), justify="center"),
                    #         shape="rectangle",
                    #         style="major",
                    #         color="secondary",
                    #         grow_x=True,
                    #         margin=2,
                    #         margin_top=0
                    #     ),
                    #     target_url="https://www.paypal.com/ncp/payment/89YMGVZ4S33RS",
                    #     open_in_new_tab=True
                    # )
                )
            ),
            MainViewContentBox(
                content=transaction_history
            ),
            align_y=0,
        )
