from typing import Optional

from rio import Column, Component, event, TextStyle, Text, Button, Row, TextInput, Spacer, TextInputChangeEvent

from src.ezgg_lan_manager import ConfigurationService, UserService, TicketingService, SeatingService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.types.Seat import Seat
from src.ezgg_lan_manager.types.User import User


class GuestsPage(Component):
    table_elements: list[Button] = []
    users_with_tickets: list[User] = []
    users_with_seats: dict[User, Seat] = {}
    user_filter: Optional[str] = None

    @event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Teilnehmer")
        user_service = self.session[UserService]
        all_users = await user_service.get_all_users()
        ticketing_service = self.session[TicketingService]
        seating_service = self.session[SeatingService]
        u_w_t = []
        u_w_s = {}
        for user in all_users:
            ticket = await ticketing_service.get_user_ticket(user.user_id)
            seat = await seating_service.get_user_seat(user.user_id)
            if ticket is not None:
                u_w_t.append(user)
            if seat is not None:
                u_w_s[user] = seat

        self.users_with_tickets = u_w_t
        self.users_with_seats = u_w_s

    def on_searchbar_content_change(self, change_event: TextInputChangeEvent) -> None:
        self.user_filter = change_event.text

    def build(self) -> Component:
        if self.user_filter:
            users = [user for user in self.users_with_tickets if self.user_filter.lower() in user.user_name or self.user_filter.lower() in str(user.user_id)]
        else:
            users = self.users_with_tickets
        self.table_elements.clear()
        for idx, user in enumerate(users):
            try:
                seat = self.users_with_seats[user]
            except KeyError:
                seat = None
            self.table_elements.append(
                Button(
                    content=Row(Text(text=f"{user.user_id:0>4}", align_x=0, margin_right=1), Text(text=user.user_name, grow_x=True, overflow="ellipsize"),
                                Text(text="-" if seat is None else seat.seat_id, align_x=1)),
                    shape="rectangle",
                    grow_x=True,
                    color=self.session.theme.hud_color if idx % 2 == 0 else self.session.theme.primary_color
                )
            )

        return Column(
            MainViewContentBox(
                Column(
                    Text(
                        text="Teilnehmer",
                        style=TextStyle(
                            fill=self.session.theme.background_color,
                            font_size=1.2
                        ),
                        margin_top=2,
                        margin_bottom=2,
                        align_x=0.5
                    ),
                    TextInput(
                        label="Suche nach Name oder ID",
                        margin=1,
                        margin_left=3,
                        margin_right=3,
                        on_change=self.on_searchbar_content_change
                    ),
                    Button(
                        content=Row(Text(text="ID  ", align_x=0, margin_right=1), Text(text="Benutzername", grow_x=True), Text(text="Sitzplatz", align_x=1)),
                        shape="rectangle",
                        grow_x=True,
                        color=self.session.theme.primary_color,
                        style="plain-text",
                        is_sensitive=False
                    ),
                    *self.table_elements,
                    Spacer(min_height=1)
                )
            ),
            align_y=0
        )
