from datetime import datetime
from decimal import Decimal
from typing import Optional

from rio import Component, Column, NumberInput, ThemeContextSwitcher, TextInput, Row, Button, EventHandler

from src.ezgg_lan_manager.types.Transaction import Transaction
from src.ezgg_lan_manager.types.User import User


class NewTransactionForm(Component):
    user: Optional[User] = None
    input_value: float = 0
    input_reason: str = ""
    new_transaction_cb: EventHandler[Transaction] = None

    async def send_debit_transaction(self) -> None:
        await self.call_event_handler(
            self.new_transaction_cb,
            Transaction(
                user_id=self.user.user_id,
                value=Decimal(str(self.input_value)),
                is_debit=True,
                reference=self.input_reason,
                transaction_date=datetime.now()
            )
        )

    async def send_credit_transaction(self) -> None:
        await self.call_event_handler(
            self.new_transaction_cb,
            Transaction(
                user_id=self.user.user_id,
                value=Decimal(str(self.input_value)),
                is_debit=False,
                reference=self.input_reason,
                transaction_date=datetime.now()
            )
        )

    def build(self) -> Component:
        return ThemeContextSwitcher(
            content=Column(
                NumberInput(
                    value=self.bind().input_value,
                    label="Betrag",
                    suffix_text="€",
                    decimals=2,
                    margin=1,
                    margin_bottom=0
                ),
                TextInput(
                    text=self.bind().input_reason,
                    label="Beschreibung",
                    margin=1,
                    margin_bottom=0
                ),
                Row(
                    Button(
                        content="Entfernen",
                        shape="rectangle",
                        color="danger",
                        margin=1,
                        on_press=self.send_debit_transaction
                    ),
                    Button(
                        content="Hinzufügen",
                        shape="rectangle",
                        color="success",
                        margin=1,
                        on_press=self.send_credit_transaction
                    )
                )
            ),
            color="primary"
        )
