import pygame
from client.data import config
import time

class GameMenu:
    def __init__(self, screen):
        self.screen = screen
        self.screen_width, self.screen_height = screen.get_size()
        self.font = pygame.font.SysFont(config.FONT_NAME, int(self.screen_height * 0.04))
        self.options = ["Options", "Main Menu", "Return"]
        self.selected = 0
        self.option_rects = []

    def handle_event(self, event):
        if not hasattr(self, "option_rects") or not self.option_rects:
            return
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.selected = (self.selected - 1) % len(self.options)
            elif event.key == pygame.K_DOWN:
                self.selected = (self.selected + 1) % len(self.options)
            elif event.key == pygame.K_RETURN:
                choice = self.options[self.selected]
                if choice == "Options":
                    print("Options clicked")
                elif choice == "Main Menu":
                    return "main_menu"
                elif choice == "Return":
                    return "return"
            elif event.key == pygame.K_ESCAPE:
                return "return"
        
        elif event.type == pygame.MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            for i, (option, rect) in enumerate(self.option_rects):
                if rect.collidepoint(mouse_x, mouse_y):
                    self.selected = i

        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_x, mouse_y = event.pos
            for i, (option, rect) in enumerate(self.option_rects):
                if rect.collidepoint(mouse_x, mouse_y):
                    if option == "Options":
                        print("Options clicked")
                    elif option == "Main Menu":
                        return "main_menu"
                    elif option == "Return":
                        return "return"
                    
    def draw(self):
        overlay = pygame.Surface((self.screen_width, self.screen_height))
        overlay.set_alpha(150)
        overlay.fill((0, 0, 0))
        self.screen.blit(overlay, (0, 0))

        # spacing and centering
        spacing = int(self.font.get_height() * 1.4)
        total_height = spacing * (len(self.options) - 1)
        start_y = (self.screen_height // 2) - (total_height // 2)

        # Store rects for consistent mouse detection
        self.option_rects = []

        for i, option in enumerate(self.options):
            color = (255, 255, 0) if i == self.selected else (255, 255, 255)
            text = self.font.render(option, True, color)
            text_rect = text.get_rect(center=(self.screen_width // 2, start_y + i * spacing))
            self.option_rects.append((option, text_rect))
            self.screen.blit(text, text_rect)

class CountdownPopup:
    def __init__(self, screen, font, duration=5):
        self.screen = screen
        self.font = font
        self.duration = duration
        self.start_time = None
        self.cancelled = False

        self.button_rect = pygame.Rect(
            screen.get_width() // 2 - 60,
            screen.get_height() // 2 + 50,
            120,
            40
        )

    def start(self):
        self.start_time = time.time()

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.button_rect.collidepoint(event.pos):
                self.cancelled = True
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            self.cancelled = True
    
    def get_remaining(self):
        """Return how many seconds are left before returning to the main menu."""
        if self.start_time is None:
            return self.duration
        elapsed = time.time() - self.start_time
        return max(0, int(self.duration - elapsed))

    def draw(self):
        overlay = pygame.Surface(self.screen.get_size())
        overlay.set_alpha(180)
        overlay.fill((0, 0, 0))
        self.screen.blit(overlay, (0, 0))

        elapsed = time.time() - self.start_time if self.start_time else 0
        remaining = max(0, int(self.duration - elapsed))

        # Draw text
        text = self.font.render(f"Returning to main menu in {remaining}...", True, (255, 255, 255))
        self.screen.blit(
            text,
            (self.screen.get_width() // 2 - text.get_width() // 2,
             self.screen.get_height() // 2 - 30)
        )

        # Draw cancel button
        mouse_pos = pygame.mouse.get_pos()
        is_hovered = self.button_rect.collidepoint(mouse_pos)
        button_color = (120, 120, 120) if is_hovered else (60, 60, 60)

        pygame.draw.rect(self.screen, button_color, self.button_rect)
        btn_text = self.font.render("Cancel", True, (255, 255, 255))
        self.screen.blit(
            btn_text,
            (self.button_rect.centerx - btn_text.get_width() // 2,
             self.button_rect.centery - btn_text.get_height() // 2)
        )

        return remaining
