from random import choice
from typing import Optional
from decimal import Decimal

from rio import Component, TextStyle, Color, Button, Text, Rectangle, Column, Row, Spacer, Link, event, EventHandler

from src.ezgg_lan_manager.components.UserInfoBoxButton import UserInfoBoxButton
from src.ezgg_lan_manager.services.LocalDataService import LocalData, LocalDataService
from src.ezgg_lan_manager.services.RefreshService import RefreshService
from src.ezgg_lan_manager.services.UserService import UserService
from src.ezgg_lan_manager.services.AccountingService import AccountingService
from src.ezgg_lan_manager.services.TicketingService import TicketingService
from src.ezgg_lan_manager.services.SeatingService import SeatingService
from src.ezgg_lan_manager.types.Seat import Seat
from src.ezgg_lan_manager.types.Ticket import Ticket
from src.ezgg_lan_manager.types.User import User
from src.ezgg_lan_manager.types.UserSession import UserSession


class StatusButton(Component):
    STYLE = TextStyle(fill=Color.from_hex("121212"), font_size=0.5)
    label: str
    target_url: str
    enabled: bool

    def build(self) -> Component:
        return Link(
            content=Button(
                content=Text(self.label, style=self.STYLE, justify="center"),
                shape="rectangle",
                style="major",
                color="success" if self.enabled else "danger",
                grow_x=True,
                margin_left=0.6,
                margin_right=0.6,
                margin_top=0.6
            ),
            target_url=self.target_url,
            align_y=0.5,
            grow_y=False
        )


class UserInfoBox(Component):
    user_id: int
    status_change_cb: EventHandler = None
    TEXT_STYLE = TextStyle(fill=Color.from_hex("02dac5"), font_size=0.9)
    user: Optional[User] = None
    user_balance: Optional[Decimal] = Decimal("0")
    user_ticket: Optional[Ticket] = None
    user_seat: Optional[Seat] = None

    @staticmethod
    def get_greeting() -> str:
        return choice(["Guten Tacho", "Tuten Gag", "Servus", "Moinjour", "Hallöchen", "Heyho", "Moinsen"])

    async def logout(self) -> None:
        self.session.detach(UserSession)
        self.user = None
        self.session[LocalDataService].del_session(self.session[LocalData].stored_session_token)
        self.session[LocalData].stored_session_token = None
        self.session.attach(self.session[LocalData])
        if self.status_change_cb is not None:
            await self.status_change_cb()
        await self.session[RefreshService].trigger_refresh()
        self.session.navigate_to("")

    @event.on_populate
    async def async_init(self) -> None:
        self.user = await self.session[UserService].get_user(self.user_id)
        if self.user is not None:
            self.user_balance = await self.session[AccountingService].get_balance(self.user.user_id)
            self.user_ticket = await self.session[TicketingService].get_user_ticket(self.user.user_id)
            self.user_seat = await self.session[SeatingService].get_user_seat(self.user.user_id)
        self.session[AccountingService].add_update_hook(self.update)

    async def update(self) -> None:
        self.user_balance = await self.session[AccountingService].get_balance(self.user_id)
        self.user_ticket = await self.session[TicketingService].get_user_ticket(self.user_id)
        self.user_seat = await self.session[SeatingService].get_user_seat(self.user_id)

    def build(self) -> Component:
        if not self.user:
            return Spacer()
        return Rectangle(
            content=Column(
                Text(f"{self.get_greeting()},", style=TextStyle(fill=Color.from_hex("02dac5"), font_size=0.9),
                     justify="center"),
                Text(f"{self.user.user_name}", style=TextStyle(fill=Color.from_hex("02dac5"), font_size=1.2),
                     justify="center"),
                Row(
                    StatusButton(label="TICKET", target_url="./buy_ticket",
                                 enabled=self.user_ticket is not None),
                    StatusButton(label="SITZPLATZ", target_url="./seating",
                                 enabled=self.user_seat is not None),
                    proportions=(50, 50),
                    grow_y=False
                ),
                UserInfoBoxButton("Profil bearbeiten", "./edit-profile"),
                UserInfoBoxButton(
                    f"Guthaben: {self.session[AccountingService].make_euro_string_from_decimal(self.user_balance)}",
                    "./account"),
                Button(
                    content=Text("Ausloggen", style=TextStyle(fill=Color.from_hex("02dac5"), font_size=0.6)),
                    shape="rectangle",
                    style="minor",
                    color="secondary",
                    grow_x=True,
                    margin_left=0.6,
                    margin_right=0.6,
                    margin_top=0.6,
                    on_press=self.logout
                )
            ),
            fill=Color.TRANSPARENT,
            min_height=8,
            min_width=12,
            align_x=0.5,
            margin_top=0.3,
            margin_bottom=1.5
        )
