from asyncio import sleep

from rio import event, ProgressCircle, PointerEventListener, PointerEvent, Popup, Color

from src.ezgg_lan_manager import ConfigurationService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.components.TeamRevealer import TeamRevealer
from src.ezgg_lan_manager.components.TeamsDialogHandler import *
from src.ezgg_lan_manager.services.RefreshService import RefreshService
from src.ezgg_lan_manager.services.TeamService import TeamService
from src.ezgg_lan_manager.services.UserService import UserService
from src.ezgg_lan_manager.types.Team import Team
from src.ezgg_lan_manager.types.User import User
from src.ezgg_lan_manager.types.UserSession import UserSession


class TeamsPage(Component):
    all_teams: Optional[list[Team]] = None
    user: Optional[User] = None

    # Dialog handling
    popup_open: bool = False
    join_active: bool = False
    leave_active: bool = True
    create_active: bool = False
    selected_team_for_join_or_leave: Optional[Team] = None

    @event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Teams")
        self.session[RefreshService].subscribe(self.on_populate)
        self.all_teams = await self.session[TeamService].get_all_teams()
        try:
            self.user = await self.session[UserService].get_user(self.session[UserSession].user_id)
        except KeyError:
            self.user = None

    async def on_join_button_pressed(self, team: Team) -> None:
        if self.user is None:
            return
        self.selected_team_for_join_or_leave = team
        self.join_active, self.leave_active, self.create_active = True, False, False
        self.popup_open = True

    async def on_leave_button_pressed(self, team: Team) -> None:
        if self.user is None:
            return
        self.selected_team_for_join_or_leave = team
        self.join_active, self.leave_active, self.create_active = False, True, False
        self.popup_open = True

    async def on_create_button_pressed(self, _: PointerEvent) -> None:
        if self.user is None:
            return
        self.join_active, self.leave_active, self.create_active = False, False, True
        self.popup_open = True

    async def popup_action_cancelled(self) -> None:
        self.popup_open = False
        await sleep(0.2)  # Waits for the animation to play before resetting its contents
        self.join_active, self.leave_active, self.create_active = False, False, False
        self.selected_team_for_join_or_leave = None
        self.all_teams = await self.session[TeamService].get_all_teams()

    def build(self) -> Component:
        if self.all_teams is None:
            return Column(
                MainViewContentBox(
                    ProgressCircle(
                        color="secondary",
                        align_x=0.5,
                        margin_top=1,
                        margin_bottom=1
                    )
                ),
                Spacer()
            )

        team_list = []
        for team in self.all_teams:
            team_list.append(
                TeamRevealer(
                    user=self.user,
                    team=team,
                    mode="leave" if self.user in team.members.keys() else "join",
                    on_button_pressed=self.on_leave_button_pressed if self.user in team.members.keys() else self.on_join_button_pressed
                )
            )

        if team_list:
            team_list[-1].margin_bottom = 1

        own_teams_content = Spacer(grow_x=False, grow_y=False)
        if self.user is not None:
            user_team_list = []
            for team in self.all_teams:
                if self.user in team.members.keys():
                    user_team_list.append(TeamRevealer(user=self.user, team=team, mode="leave", on_button_pressed=self.on_leave_button_pressed))

            if not user_team_list:
                user_team_list.append(Text(
                    text="Du bist noch in keinem Team.",
                    style=TextStyle(
                        fill=self.session.theme.background_color,
                        font_size=1
                    ),
                    margin_top=1,
                    margin_bottom=1,
                    align_x=0.5
                ))
            else:
                user_team_list[-1].margin_bottom = 1
            own_teams_content = MainViewContentBox(
                Column(
                    Row(
                        Text(
                            text="Deine Teams",
                            style=TextStyle(
                                fill=self.session.theme.background_color,
                                font_size=1.2
                            ),
                            grow_x=True,
                            justify="right",
                            margin_right=3
                        ),
                        Column(
                            PointerEventListener(Rectangle(
                                content=Text(text="Team erstellen", style=TextStyle(fill=self.session.theme.background_color, font_size=0.7), margin=0.1, selectable=False),
                                stroke_width=0.1,
                                stroke_color=self.session.theme.hud_color,
                                cursor="pointer",
                                hover_fill=self.session.theme.hud_color,
                                transition_time=0
                            ), on_press=self.on_create_button_pressed),
                            Spacer(),
                            margin_right=2
                        ),
                        margin_top=1,
                        margin_bottom=1
                    ),
                    *user_team_list
                )
            )

        return Popup(
            anchor=Column(
                own_teams_content,
                MainViewContentBox(
                    Column(
                        Text(
                            text="Alle Teams",
                            style=TextStyle(
                                fill=self.session.theme.background_color,
                                font_size=1.2
                            ),
                            margin_top=1,
                            margin_bottom=1,
                            align_x=0.5
                        ),
                        *team_list
                    )
                ),
                align_y=0,
            ),
            content=Column(
                TeamsDialogJoinHandler(is_active=self.join_active, cancel=self.popup_action_cancelled, user=self.user, team=self.selected_team_for_join_or_leave),
                TeamsDialogLeaveHandler(is_active=self.leave_active, cancel=self.popup_action_cancelled, user=self.user, team=self.selected_team_for_join_or_leave),
                TeamsDialogCreateHandler(is_active=self.create_active, cancel=self.popup_action_cancelled, user=self.user)
            ),
            is_open=self.popup_open,
            modal=False,
            corner_radius=(0.5, 0.5, 0.5, 0.5),
            color=Color.TRANSPARENT,
            user_closable=False,
            position="top"
        )
