"""
Create Profile Screen
Virtual keyboard interface for creating new user profiles
"""

from .base_screen import BaseScreen


class CreateProfileScreen(BaseScreen):
    """Profile creation screen with virtual keyboard"""
    
    def __init__(self, data_manager, ui_renderer, screen_manager):
        super().__init__(data_manager, ui_renderer, screen_manager)
        
        # Virtual keyboard layout
        self.virtual_keyboard = [
            ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
            ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'],
            ['U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3'],
            ['4', '5', '6', '7', '8', '9', ' ', '.', '-', '_'],
            ['<DEL', 'SPACE', 'DONE', 'CANCEL']
        ]
        
        # Screen state
        self.input_text = ""
        self.input_active = False
        self.vk_cursor_x = 0
        self.vk_cursor_y = 0
    
    def render(self) -> None:
        """Render profile creation screen"""
        self.ui_renderer.draw_header("Create Profile")
        
        # Input field
        placeholder = "Profile Name" if not self.input_text else ""
        self.ui_renderer.draw_input_field(self.input_text, 120, 90, 400, 30, 
                                         self.input_active, placeholder)
        
        if self.input_active:
            # Virtual keyboard
            self.ui_renderer.draw_virtual_keyboard(self.virtual_keyboard, 
                                                  self.vk_cursor_x, self.vk_cursor_y)
            help_text = "Arrows: Navigate • Enter: Select • Escape: Cancel"
        else:
            self.ui_renderer.draw_text("Press Enter to start typing", 320, 150, 
                                      'yellow', 'medium', center=True)
            self.ui_renderer.draw_button("← Back", 270, 200, 100, 30, True)
            help_text = "Enter: Start Input • Escape: Back"
        
        self.ui_renderer.draw_footer_help(help_text)
    
    def handle_input(self, action: str) -> bool:
        """Handle create profile input"""
        if self.input_active:
            # Virtual keyboard navigation
            if action == 'up':
                self.vk_cursor_y = max(0, self.vk_cursor_y - 1)
                max_x = len(self.virtual_keyboard[self.vk_cursor_y]) - 1
                self.vk_cursor_x = min(self.vk_cursor_x, max_x)
                return True
            elif action == 'down':
                max_y = len(self.virtual_keyboard) - 1
                self.vk_cursor_y = min(max_y, self.vk_cursor_y + 1)
                max_x = len(self.virtual_keyboard[self.vk_cursor_y]) - 1
                self.vk_cursor_x = min(self.vk_cursor_x, max_x)
                return True
            elif action == 'left':
                self.vk_cursor_x = max(0, self.vk_cursor_x - 1)
                return True
            elif action == 'right':
                max_x = len(self.virtual_keyboard[self.vk_cursor_y]) - 1
                self.vk_cursor_x = min(max_x, self.vk_cursor_x + 1)
                return True
            elif action == 'confirm':
                self.handle_virtual_keyboard_input()
                return True
            elif action == 'back':
                self.input_active = False
                return True
        else:
            # Initial screen navigation
            if action == 'confirm':
                self.input_active = True
                self.vk_cursor_x = 0
                self.vk_cursor_y = 0
                return True
            elif action == 'back':
                self.handle_back()
                return True
            elif action == 'delete' and self.input_text:
                self.input_text = self.input_text[:-1]
                return True
        
        return False
    
    def handle_virtual_keyboard_input(self) -> None:
        """Handle virtual keyboard character selection"""
        if (self.vk_cursor_y >= len(self.virtual_keyboard) or 
            self.vk_cursor_x >= len(self.virtual_keyboard[self.vk_cursor_y])):
            return
        
        selected_char = self.virtual_keyboard[self.vk_cursor_y][self.vk_cursor_x]
        
        if selected_char == '<DEL':
            if self.input_text:
                self.input_text = self.input_text[:-1]
        elif selected_char == 'SPACE':
            if len(self.input_text) < 20:
                self.input_text += ' '
        elif selected_char == 'DONE':
            if self.input_text.strip():
                success, message = self.data_manager.create_profile(self.input_text)
                if success:
                    self.screen_manager.set_screen("main_menu")
                    self.input_active = False
                    self.input_text = ""
                else:
                    self.show_error(message)
            else:
                self.show_error("Profile name cannot be empty!")
        elif selected_char == 'CANCEL':
            self.input_text = ""
            self.input_active = False
        else:
            if len(self.input_text) < 20:
                self.input_text += selected_char
    
    def reset_state(self) -> None:
        """Reset screen state when entering"""
        super().reset_state()
        self.input_text = ""
        self.input_active = False
        self.vk_cursor_x = 0
        self.vk_cursor_y = 0
    
    def get_help_text(self) -> str:
        """Get help text for create profile"""
        if self.input_active:
            return "Arrows: Navigate • Enter: Select • Escape: Cancel"
        else:
            return "Enter: Start Input • Escape: Back"
