"""
Screen Manager Module
Manages individual screen modules and navigation between them
"""

from typing import Dict, Optional
from screens import (
    BaseScreen,
    MainMenuScreen,
    ProfileListScreen,
    CreateProfileScreen,
    EditProfileScreen,
    LeaderboardScreen,
    ProfileStatsScreen
)


class ModularScreenManager:
    """Manages individual screen modules and navigation"""
    
    def __init__(self, data_manager, ui_renderer):
        """
        Initialize screen manager with all screen modules
        
        Args:
            data_manager: ProfileDataManager instance
            ui_renderer: UIRenderer instance
        """
        self.data_manager = data_manager
        self.ui_renderer = ui_renderer
        
        # Current screen state
        self.current_screen_name = "main_menu"
        self.screens: Dict[str, BaseScreen] = {}
        
        # Initialize all screen modules
        self._initialize_screens()
        
        # Error state
        self.show_error = False
        self.error_message = ""
        self.error_timer = 0
    
    def _initialize_screens(self) -> None:
        """Initialize all screen module instances"""
        self.screens = {
            "main_menu": MainMenuScreen(self.data_manager, self.ui_renderer, self),
            "profile_list": ProfileListScreen(self.data_manager, self.ui_renderer, self),
            "create_profile": CreateProfileScreen(self.data_manager, self.ui_renderer, self),
            "edit_profile": EditProfileScreen(self.data_manager, self.ui_renderer, self),
            "leaderboard": LeaderboardScreen(self.data_manager, self.ui_renderer, self),
            "profile_stats": ProfileStatsScreen(self.data_manager, self.ui_renderer, self)
        }
    
    def set_screen(self, screen_name: str) -> None:
        """
        Switch to a different screen
        
        Args:
            screen_name: Name of the screen to switch to
        """
        if screen_name in self.screens:
            self.current_screen_name = screen_name
            # Reset state when entering new screen
            self.screens[screen_name].reset_state()
        else:
            print(f"Warning: Unknown screen '{screen_name}'")
    
    def get_current_screen(self) -> Optional[BaseScreen]:
        """Get the current active screen module"""
        return self.screens.get(self.current_screen_name)
    
    def handle_input(self, action: str) -> bool:
        """
        Handle input by delegating to current screen
        
        Args:
            action: Input action string
            
        Returns:
            bool: True if input was handled and app should continue, False to exit
        """
        # Dismiss error dialog on any input
        if self.show_error:
            self.show_error = False
            return True
        
        current_screen = self.get_current_screen()
        if current_screen:
            result = current_screen.handle_input(action)
            
            # Handle special case for main menu exit
            if self.current_screen_name == "main_menu" and action == 'back':
                return False  # Exit application
                
            return result if result is not None else True
        
        return True
    
    def render(self) -> None:
        """Render current screen and any overlays"""
        current_screen = self.get_current_screen()
        if current_screen:
            current_screen.render()
        
        # Render error dialog if active
        if self.show_error:
            import time
            self.ui_renderer.draw_error_dialog(self.error_message)
            # Auto-dismiss after timer
            if time.time() > self.error_timer:
                self.show_error = False
    
    def show_error_dialog(self, message: str) -> None:
        """
        Show an error dialog overlay
        
        Args:
            message: Error message to display
        """
        import time
        self.show_error = True
        self.error_message = message
        self.error_timer = time.time() + 3.0
    
    @property
    def current_screen(self) -> str:
        """Get current screen name (for compatibility)"""
        return self.current_screen_name
    
    @property
    def selected_index(self) -> int:
        """Get selected index from current screen (for compatibility)"""
        current_screen = self.get_current_screen()
        return current_screen.selected_index if current_screen else 0
    
    @selected_index.setter
    def selected_index(self, value: int) -> None:
        """Set selected index on current screen (for compatibility)"""
        current_screen = self.get_current_screen()
        if current_screen:
            current_screen.selected_index = value
