from typing import Literal, Callable

from rio import Component, PointerEventListener, Rectangle, Image, Text, Tooltip, TextStyle, Color, Icon, Row, PointerEvent

from from_root import from_root

from src.ezgg_lan_manager.types.TournamentBase import TournamentStatus


class TournamentPageRow(Component):
    tournament_id: int
    tournament_name: str
    game_image_name: str
    current_participants: int
    max_participants: int
    tournament_status: TournamentStatus
    clicked_cb: Callable

    def handle_click(self, _: PointerEvent) -> None:
        self.clicked_cb(self.tournament_id)

    def determine_tournament_status_icon_color_and_text(self) -> tuple[str, Literal["success", "warning", "danger"], str]:
        if self.tournament_status == TournamentStatus.OPEN:
            return "material/lock_open", "success", "Anmeldung geöffnet"
        elif self.tournament_status == TournamentStatus.CLOSED:
            return "material/lock", "danger", "Anmeldung geschlossen"
        elif self.tournament_status == TournamentStatus.ONGOING:
            return "material/autoplay", "warning", "Turnier läuft"
        elif self.tournament_status == TournamentStatus.COMPLETED:
            return "material/check_circle", "success", "Turnier beendet"
        elif self.tournament_status == TournamentStatus.CANCELED:
            return "material/cancel", "danger", "Turnier abgesagt"
        elif self.tournament_status == TournamentStatus.INVITE_ONLY:
            return "material/person_cancel", "warning", "Teilnahme nur per Einladung"
        else:
            raise RuntimeError(f"Unknown tournament status: {str(self.tournament_status)}")

    def build(self) -> Component:
        icon_name, color, text = self.determine_tournament_status_icon_color_and_text()
        return PointerEventListener(
            content=Rectangle(
                content=Row(
                    Image(image=from_root(f"src/ezgg_lan_manager/assets/img/games/{self.game_image_name}")),
                    Text(self.tournament_name, style=TextStyle(fill=self.session.theme.background_color, font_size=1)),
                    Text(f"{self.current_participants}/{self.max_participants}", style=TextStyle(fill=self.session.theme.background_color, font_size=1), justify="right", margin_right=0.5),
                    Tooltip(anchor=Icon(icon_name, min_width=1, min_height=1, fill=color), position="top",
                            tip=Text(text, style=TextStyle(fill=self.session.theme.background_color, font_size=0.7))),
                    proportions=[1, 4, 1, 1],
                    margin=.5
                ),
                fill=self.session.theme.hud_color,
                margin=1,
                margin_bottom=0,
                stroke_color=Color.TRANSPARENT,
                stroke_width=0.2,
                hover_stroke_color=self.session.theme.background_color,
                cursor="pointer"
            ),
            on_press=self.handle_click
        )
