from textual import on
import logging
from textual.app import App, ComposeResult
from textual.containers import Container, Vertical, Horizontal
from textual.widgets import Header, Footer, Button, Input, Static, Label, SelectionList, Checkbox
from textual.screen import Screen
from textual.binding import Binding
import random
from textual import log
import os

WORTLISTEN = {'custom.txt': [('Rückkopplung', ' Technik AG\n'), ('Herr Beck', ' SFZ\n'), ('Bowl', ' teuer\n'),
                             ('Stuhllehne', ' Matthias\n'), ('O-saal', ' sofa\n'), ('hochwasser-warnapp', ' bach \n'),
                             ('Bahnhof', ' Reise\n'), ('Biberach', ' Großstadt\n'), ('jugendherrberge', ' billig\n'),
                             ('Brezel', ' -\n'), ('Leberkäsweckle', ' Mensa\n'), ('Flugzeug', ' TODO\n'),
                             ('Laptop', ' schwarz\n'), ('Döner', ' teuer\n'), ('Fahrradweg', ' rot\n'),
                             ('Lehrerzimmer', ' Area 51\n'), ('Red Carpet', ' Fernseher\n'), ('Nachtumzug', ' -\n'),
                             ('Bundeskanzler', ' TODO\n'), ('Impostor', ' du\n'), ('Kunstlehrer:in', ' Schule\n'),
                             ('Strohhut', ' hot')],
              'test.txt': [('test', ' tests')]}



class PlayerSetupScreen(Screen):
    """Screen for adding players."""

    BINDINGS = [
        Binding("escape", "quit", "Quit"),
    ]

    def __init__(self):
        super().__init__()
        self.players = []

    def compose(self) -> ComposeResult:
        yield Header()
        yield Container(
            Static("Imposchtor", id="title"),
            Static("Spieler hinzufügen (mindestens 3)", id="subtitle"),
            Horizontal(
                Input(placeholder="Name...", id="player_input"),
                Button("Hinzufügen", variant="primary", id="add_btn"),
                id="input_row"
            ),
            Container(id="player_list"),
            Button("Weiter", variant="success", id="start_btn", disabled=True),
            id="setup_container"
        )
        yield Footer()

    def on_mount(self) -> None:
        self.query_one("#player_input").focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "add_btn":
            self.add_player()
        elif event.button.id == "start_btn":
            self.next_screen()
        elif event.button.id and event.button.id.startswith("remove_"):
            player_name = event.button.id.replace("remove_", "")
            self.remove_player(player_name)

    def on_input_submitted(self, event: Input.Submitted) -> None:
        if event.input.id == "player_input":
            self.add_player()

    def add_player(self) -> None:
        input_widget = self.query_one("#player_input", Input)
        name = input_widget.value.strip()

        if name and name not in self.players:
            self.players.append(name)
            input_widget.value = ""
            self.update_player_list()
            input_widget.focus()

    def remove_player(self, name: str) -> None:
        if name in self.players:
            self.players.remove(name)
            self.update_player_list()

    def update_player_list(self) -> None:
        container = self.query_one("#player_list")
        container.remove_children()

        for player in self.players:
            player_row = Horizontal(
                Static(f"👤 {player}", classes="player_name"),
                Button("Entfernen", variant="error", id=f"remove_{hash(player)}", classes="remove_btn"),
                classes="player_row"
            )
            container.mount(player_row)

        start_btn = self.query_one("#start_btn", Button)
        start_btn.disabled = len(self.players) < 3

    def next_screen(self):
        if len(self.players) >= 3:
            self.app.start_wordlist_selection(self.players)


class SelectionListApp(Screen):
    # CSS_PATH = "selection_list.tcss"
    def __init__(self):
        super().__init__()
        self.wortlisten = WORTLISTEN
        self.hilfswörter = True

    def compose(self) -> ComposeResult:
        log([(x, i, False) for i, x in enumerate(self.wortlisten.keys())])

        yield Header()
        yield SelectionList[str](
            *[(x, x, False) for x in self.wortlisten.keys()]
        )
        yield Horizontal(Button("Spiel starten", variant="success", id="start_btn", disabled=True))
        yield Horizontal(Checkbox("Mit Hilfswörtern", True, id="hilfswort"))
        yield Footer()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "start_btn":
            self.start_game()

    def on_checkbox_changed(self):
        self.hilfswörter = not self.hilfswörter

    @on(SelectionList.SelectedChanged)
    def update_selected_view(self) -> None:
        self.query_one(Button).disabled = len(self.query_one(SelectionList).selected) == 0

    def start_game(self) -> None:
        sl: SelectionList = self.query_one(SelectionList)
        selected = [k for i, k in self.wortlisten.items() if i in sl.selected]
        if len(selected) >= 1:
            self.app.start_game(selected, self.hilfswörter)


class WordRevealScreen(Screen):
    """Screen for revealing words to each player."""

    BINDINGS = [
        Binding("escape", "quit", "Quit"),
    ]

    def __init__(self, player_name: str, word: str, is_impostor: bool, player_num: int, total_players: int):
        super().__init__()
        self.player_name = player_name
        self.word = word
        self.is_impostor = is_impostor
        self.player_num = player_num
        self.total_players = total_players
        self.word_revealed = False

    def compose(self) -> ComposeResult:
        yield Header()
        yield Container(
            Static(f"Spieler {self.player_num} von {self.total_players}", id="progress"),
            Static(f"👤 {self.player_name}", id="player_name_display"),
            Static("Drücke 'S' um dein Wort zu zeigen", id="instruction"),
            Static("", id="word_display"),
            Static("", id="role_hint"),
            Button("Weiter →", variant="primary", id="next_btn", disabled=True),
            id="reveal_container"
        )
        yield Footer()

    def on_key(self, event) -> None:
        if event.key == "s":
            self.reveal_word()

    def reveal_word(self) -> None:
        if not self.word_revealed:
            self.word_revealed = True
            word_display = self.query_one("#word_display")
            role_hint = self.query_one("#role_hint")
            instruction = self.query_one("#instruction")

            if self.is_impostor:
                word_display.update(f"Hilfswort: {self.word}")
                role_hint.update("Du bist der IMPOSTOR")
                role_hint.add_class("impostor_hint")
            else:
                word_display.update(f"Wort: {self.word}")
                role_hint.update("Du bist nicht der Impostor")
                role_hint.add_class("player_hint")

            word_display.add_class("word_revealed")
            instruction.update("Merke dir das Wort und drücke 'Weiter'")

            next_btn = self.query_one("#next_btn", Button)
            next_btn.disabled = False

    def hide_word(self) -> None:
        if self.word_revealed:
            self.word_revealed = False
            word_display = self.query_one("#word_display")
            role_hint = self.query_one("#role_hint")
            instruction = self.query_one("#instruction")

            word_display.update(f"")
            role_hint.update("")

            word_display.add_class("word_revealed")
            instruction.update("")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "next_btn" and self.word_revealed:
            self.app.next_player()


class GameScreen(Screen):
    """Main game screen with timer."""

    BINDINGS = [
        Binding("r", "restart", "Neues Spiel"),
        Binding("escape", "quit", "Quit"),
    ]

    def __init__(self, starting_player: str, all_players: list):
        super().__init__()
        self.starting_player = starting_player
        self.all_players = all_players
        self.elapsed_seconds = 0

    def compose(self) -> ComposeResult:
        yield Header()
        yield Container(
            Static("Spiel läuft", id="game_title"),
            Static(f"{self.starting_player} beginnt", id="starting_player"),
            Static("Alle Spieler:", id="players_label"),
            Container(id="all_players_list"),
            Static("", id="timer_display"),
            # Static("\n💡 Tip: Discuss and find the impostor!", id="tip"),
            Button("Neus Spiel", variant="warning", id="restart_btn"),
            id="game_container"
        )
        yield Footer()

    def on_mount(self) -> None:
        # Display all players
        players_container = self.query_one("#all_players_list")
        for player in self.all_players:
            if player == self.starting_player:
                players_container.mount(Static(f"▶️  {player}", classes="player_item"))
            else:
                players_container.mount(Static(f"   {player}", classes="player_item"))

        # Start timer
        self.set_interval(1, self.update_timer)

    def update_timer(self) -> None:
        self.elapsed_seconds += 1
        minutes = self.elapsed_seconds // 60
        seconds = self.elapsed_seconds % 60
        timer_display = self.query_one("#timer_display")
        timer_display.update(f"⏱️  Zeit: {minutes:02d}:{seconds:02d}")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "restart_btn":
            self.action_restart()

    def action_restart(self) -> None:
        self.app.restart_game()


class ImpostorApp(App):
    """Main application."""

    CSS = """
    Screen {
        align: center middle;
    }

    #title {
        text-align: center;
        text-style: bold;
        color: $accent;
        margin: 1;
        content-align: center middle;
    }

    #subtitle {
        text-align: center;
        color: $text-muted;
        margin-bottom: 2;
    }

    #setup_container {
        width: 60;
        height: auto;
        border: solid $primary;
        padding: 2;
    }

    #input_row {
        height: 3;
        margin: 1;
    }

    #player_input {
        width: 3fr;
    }

    #add_btn {
        width: 1fr;
    }

    #player_list {
        height: auto;
        max-height: 20;
        overflow-y: auto;
        margin: 1 0;
    }

    .player_row {
        height: 3;
        margin: 0 0 1 0;
    }

    .player_name {
        width: 3fr;
        padding: 1;
    }

    .remove_btn {
        width: 1fr;
    }

    #start_btn {
        width: 100%;
        margin-top: 1;
    }

    #reveal_container {
        width: 60;
        height: auto;
        border: solid $primary;
        padding: 3;
    }

    #progress {
        text-align: center;
        color: $text-muted;
        margin-bottom: 1;
    }

    #player_name_display {
        text-align: center;
        text-style: bold;
        color: $success;
        margin: 1;
    }

    #instruction {
        text-align: center;
        color: $warning;
        margin: 2;
    }

    #word_display {
        text-align: center;
        text-style: bold;
        margin: 2;
        min-height: 3;
    }

    .word_revealed {
        color: $accent;
    }

    #role_hint {
        text-align: center;
        margin: 1;
        min-height: 2;
    }

    .impostor_hint {
        color: $error;
    }

    .player_hint {
        color: $success;
    }

    #next_btn {
        width: 100%;
        margin-top: 2;
    }

    #game_container {
        width: 60;
        height: auto;
        border: solid $success;
        padding: 3;
    }

    #game_title {
        text-align: center;
        text-style: bold;
        color: $success;
        margin-bottom: 2;
    }

    #starting_player {
        text-align: center;
        text-style: bold;
        color: $accent;
        margin: 2;
    }

    #players_label {
        text-align: center;
        color: $text-muted;
        margin-top: 2;
    }

    #all_players_list {
        height: auto;
        margin: 1 0;
        text-align: center;
    }

    .player_item {
        text-align: center;
        margin: 0;
    }

    #timer_display {
        text-align: center;
        text-style: bold;
        color: $warning;
        margin: 2;
    }

    #tip {
        text-align: center;
        color: $text-muted;
        margin: 2;
    }

    #restart_btn {
        width: 100%;
        margin-top: 2;
    }
    """

    def __init__(self):
        super().__init__()
        self.players = []
        self.impostor = None
        self.main_word = None
        self.impostor_word = None
        self.current_player_index = 0

        self.hint_enbled = True

        # Word pairs (main word, impostor hint)
        # self.wortlisten = load_wordlists()

    def on_mount(self) -> None:
        self.push_screen(PlayerSetupScreen())

    def start_wordlist_selection(self, players: list):
        self.players = players.copy()
        self.push_screen(SelectionListApp())

    def start_game(self, word_lists: dict[list[tuple]], hilfswörter) -> None:
        random.shuffle(self.players)
        # Select random word pair
        self.main_word, self.impostor_word = random.choice([w for l in word_lists for w in l])
        if not hilfswörter:
            self.impostor_word = ""
        # Select random impostor
        self.impostor = random.choice(self.players)

        # Start word reveal sequence
        self.current_player_index = 0
        self.show_next_reveal_screen()

    def show_next_reveal_screen(self) -> None:
        if self.current_player_index < len(self.players):
            player = self.players[self.current_player_index]
            is_impostor = (player == self.impostor)
            word = self.impostor_word if is_impostor else self.main_word

            screen = WordRevealScreen(
                player,
                word,
                is_impostor,
                self.current_player_index + 1,
                len(self.players)
            )
            self.push_screen(screen)
        else:
            # All players have seen their words, start the game
            starting_player = random.choice(self.players)
            self.push_screen(GameScreen(starting_player, self.players))

    def next_player(self) -> None:
        self.pop_screen()
        self.current_player_index += 1
        self.show_next_reveal_screen()

    def restart_game(self) -> None:
        # Pop all screens except the base
        while len(self.screen_stack) > 1:
            self.pop_screen()
        self.push_screen(PlayerSetupScreen())


app = ImpostorApp()
app.run()
