import pygame
import random
import sys

# Initialize Pygame
pygame.init()

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
GREEN = (50, 200, 100)
BLUE = (50, 150, 255)
GRAY = (180, 180, 180)
DARK_GRAY = (80, 80, 80)

# Window settings
WIDTH, HEIGHT = 900, 650
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Random Name Picker")
clock = pygame.time.Clock()
FPS = 60

# Fonts
font_large = pygame.font.Font(None, 128)
font_medium = pygame.font.Font(None, 52)
font_small = pygame.font.Font(None, 36)

# Student list (feel free to modify)
students = [
    "Alice", "Bob", "Charlie", "David", "Emma",
    "Frank", "Grace", "Henry", "Ivy", "Jack",
    "Kate", "Leo", "Mia", "Noah", "Olivia",
    "Paul", "Quinn", "Rose", "Sam", "Tina"
]

# State variables
current_name = "Click Start!"
is_spinning = False
spin_start_time = 0
spin_duration = 3500  # milliseconds
last_change_time = 0
change_interval = 25   # initial interval (ms)
selected_student = None
history = []

def draw_button(text, x, y, width, height, color, hover_color):
    """Draw a button and return True if clicked"""
    mouse_x, mouse_y = pygame.mouse.get_pos()
    clicked = False
    
    # Hover effect
    if x <= mouse_x <= x + width and y <= mouse_y <= y + height:
        pygame.draw.rect(screen, hover_color, (x, y, width, height), border_radius=12)
        if pygame.mouse.get_pressed()[0]:
            clicked = True
    else:
        pygame.draw.rect(screen, color, (x, y, width, height), border_radius=12)
    
    # Border
    pygame.draw.rect(screen, WHITE, (x, y, width, height), 3, border_radius=12)
    
    # Text
    text_surface = font_small.render(text, True, WHITE)
    text_rect = text_surface.get_rect(center=(x + width//2, y + height//2))
    screen.blit(text_surface, text_rect)
    
    return clicked

def draw_history():
    """Draw pick history"""
    title = font_small.render("Pick History:", True, GRAY)
    screen.blit(title, (30, 480))
    
    y_offset = 525
    for i, name in enumerate(reversed(history[-6:])):
        text = f"{len(history)-i}. {name}"
        surface = font_small.render(text, True, GRAY)
        screen.blit(surface, (50, y_offset + i * 35))

def draw_info_panel():
    """Draw statistics panel"""
    total = len(students)
    picked = len(history)
    remaining = total - picked
    
    stats = [
        f"Total Students: {total}",
        f"Already Picked: {picked}",
        f"Remaining: {remaining}"
    ]
    
    x_start = WIDTH - 280
    y_start = 485
    for i, stat in enumerate(stats):
        text = font_small.render(stat, True, GRAY)
        screen.blit(text, (x_start, y_start + i * 38))

def main():
    global current_name, is_spinning, spin_start_time, last_change_time
    global change_interval, selected_student, history
    
    running = True
    
    while running:
        dt = clock.tick(FPS)
        current_time = pygame.time.get_ticks()
        
        # Event handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # Check "Start Pick" button
                if not is_spinning:
                    btn_rect = pygame.Rect(WIDTH//2 - 190, 420, 180, 65)
                    if btn_rect.collidepoint(event.pos):
                        is_spinning = True
                        spin_start_time = current_time
                        change_interval = 25
                        selected_student = None
                
                # Check "Reset" button
                btn_reset = pygame.Rect(WIDTH//2 + 30, 420, 145, 65)
                if btn_reset.collidepoint(event.pos):
                    history.clear()
                    current_name = "Click Start!"
                    selected_student = None
        
        # Update spinning animation
        if is_spinning:
            elapsed = current_time - spin_start_time
            
            if elapsed < spin_duration:
                # Gradually slow down
                progress = elapsed / spin_duration
                current_interval = int(25 + progress * 475)  # from 25ms to 500ms
                
                if current_time - last_change_time > current_interval:
                    current_name = random.choice(students)
                    last_change_time = current_time
            else:
                # Stop spinning, pick final result
                is_spinning = False
                selected_student = random.choice(students)
                current_name = selected_student
                history.append(selected_student)
        
        # Draw everything
        screen.fill(BLACK)
        
        # Title
        title_text = font_medium.render("🎯 Random Name Picker", True, BLUE)
        title_rect = title_text.get_rect(center=(WIDTH//2, 75))
        screen.blit(title_text, title_rect)
        
        # Display area
        display_bg = pygame.Rect(100, 140, WIDTH - 210, 240)
        pygame.draw.rect(screen, DARK_GRAY, display_bg, border_radius=18)
        pygame.draw.rect(screen, BLUE, display_bg, 4, border_radius=18)
        
        # Name display
        if selected_student and not is_spinning:
            name_color = GREEN
        elif is_spinning:
            name_color = RED
        else:
            name_color = WHITE
        
        name_text = font_large.render(current_name, True, name_color)
        name_rect = name_text.get_rect(center=(WIDTH//2, 265))
        screen.blit(name_text, name_rect)
        
        # Hint text
        if not is_spinning and not selected_student:
            hint = font_small.render("Press the button below to start!", True, GRAY)
            hint_rect = hint.get_rect(center=(WIDTH//2, 320))
            screen.blit(hint, hint_rect)
        elif selected_student:
            result_hint = font_small.render(f"🎉 Congratulations {selected_student}!", True, GREEN)
            result_rect = result_hint.get_rect(center=(WIDTH//2, 335))
            screen.blit(result_hint, result_rect)
        
        # Buttons
        btn_color = GRAY if is_spinning else GREEN
        btn_hover = (100, 225, 135) if not is_spinning else GRAY
        draw_button("Start Pick", WIDTH//2 - 195, 415, 185, 58, btn_color, btn_hover)
        
        draw_button("Reset", WIDTH//2 + 30, 416, 155, 57, RED, (215, 85, 82))
        
        # History and info panels
        draw_history()
        draw_info_panel()
        
        # Footer
        footer_text = font_small.render(f"Students: {len(students)} | Picked: {len(history)}", True, GRAY)
        screen.blit(footer_text, (30, 610))
        
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()