"""
Custom Keyboard Widget for Signage Player
Provides an on-screen keyboard for text input
"""

from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.animation import Animation
from kivy.logger import Logger
from kivy.core.window import Window
from kivy.graphics import Color, RoundedRectangle

class KeyboardWidget(FloatLayout):
    """Custom on-screen keyboard widget"""
    
    def __init__(self, **kwargs):
        super(KeyboardWidget, self).__init__(**kwargs)
        self.target_input = None
        self.size_hint = (None, None)
        
        # Calculate size - half screen width
        self.width = Window.width * 0.5
        self.height = self.width / 3
        
        # Position at bottom center
        self.x = (Window.width - self.width) / 2
        self.y = 0
        
        # Start hidden
        self.opacity = 0
        
        # Create the keyboard UI
        self._build_keyboard()
        
        # Bind window resize
        Window.bind(on_resize=self._on_window_resize)
        
        Logger.info(f"KeyboardWidget: Initialized at ({self.x}, {self.y}) with size {self.width}x{self.height}")
    
    def _build_keyboard(self):
        """Build the keyboard UI"""
        # Background
        with self.canvas.before:
            Color(0.1, 0.1, 0.1, 0.95)
            self.bg_rect = RoundedRectangle(pos=self.pos, size=self.size, radius=[15, 15, 0, 0])
        
        self.bind(pos=self._update_bg, size=self._update_bg)
        
        # Main layout
        main_layout = BoxLayout(orientation='vertical', padding=5, spacing=5)
        main_layout.size = self.size
        main_layout.pos = self.pos
        
        # Close button bar
        close_bar = BoxLayout(orientation='horizontal', size_hint=(1, None), height=40, padding=[5, 0])
        close_bar.add_widget(Widget())
        close_btn = Button(text='✕', size_hint=(None, 1), width=40, 
                          background_color=(0.8, 0.2, 0.2, 0.9), font_size='20sp', bold=True)
        close_btn.bind(on_press=lambda x: self.hide_keyboard())
        close_bar.add_widget(close_btn)
        main_layout.add_widget(close_bar)
        
        # Number row
        self._add_key_row(main_layout, ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])
        
        # Top letter row
        self._add_key_row(main_layout, ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'])
        
        # Middle letter row (with offset)
        middle_row = BoxLayout(size_hint=(1, 1), spacing=3)
        middle_row.add_widget(Widget(size_hint=(0.5, 1)))
        for letter in ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L']:
            btn = Button(text=letter)
            btn.bind(on_press=lambda x, l=letter: self.key_pressed(l.lower()))
            middle_row.add_widget(btn)
        middle_row.add_widget(Widget(size_hint=(0.5, 1)))
        main_layout.add_widget(middle_row)
        
        # Bottom letter row (with offset)
        bottom_row = BoxLayout(size_hint=(1, 1), spacing=3)
        bottom_row.add_widget(Widget(size_hint=(1, 1)))
        for letter in ['Z', 'X', 'C', 'V', 'B', 'N', 'M']:
            btn = Button(text=letter)
            btn.bind(on_press=lambda x, l=letter: self.key_pressed(l.lower()))
            bottom_row.add_widget(btn)
        bottom_row.add_widget(Widget(size_hint=(1, 1)))
        main_layout.add_widget(bottom_row)
        
        # Space and backspace row
        last_row = BoxLayout(size_hint=(1, 1), spacing=3)
        backspace_btn = Button(text='←', size_hint=(0.3, 1), font_size='24sp')
        backspace_btn.bind(on_press=lambda x: self.key_pressed('backspace'))
        last_row.add_widget(backspace_btn)
        space_btn = Button(text='Space', size_hint=(0.7, 1))
        space_btn.bind(on_press=lambda x: self.key_pressed(' '))
        last_row.add_widget(space_btn)
        main_layout.add_widget(last_row)
        
        self.add_widget(main_layout)
    
    def _add_key_row(self, parent, keys):
        """Add a row of keys"""
        row = BoxLayout(size_hint=(1, 1), spacing=3)
        for key in keys:
            btn = Button(text=key)
            btn.bind(on_press=lambda x, k=key: self.key_pressed(k.lower() if k.isalpha() else k))
            row.add_widget(btn)
        parent.add_widget(row)
    
    def _update_bg(self, *args):
        """Update background rectangle"""
        self.bg_rect.pos = self.pos
        self.bg_rect.size = self.size
    
    def _on_window_resize(self, window, width, height):
        """Handle window resize"""
        self.width = width * 0.5
        self.height = self.width / 3
        self.x = (width - self.width) / 2
        self.y = 0
    
    def show_keyboard(self, target_input):
        """Show the keyboard for a specific TextInput"""
        self.target_input = target_input
        Logger.info(f"KeyboardWidget: Showing keyboard for {target_input}")
        
        # Animate keyboard appearing
        anim = Animation(opacity=1, duration=0.2)
        anim.start(self)
    
    def hide_keyboard(self):
        """Hide the keyboard"""
        Logger.info("KeyboardWidget: Hiding keyboard")
        
        # Animate keyboard disappearing
        anim = Animation(opacity=0, duration=0.2)
        anim.start(self)
        
        # Clear target
        if self.target_input:
            self.target_input.focus = False
            self.target_input = None
    
    def key_pressed(self, key):
        """Handle key press"""
        if not self.target_input:
            return
        
        if key == 'backspace':
            # Remove last character
            if self.target_input.text:
                self.target_input.text = self.target_input.text[:-1]
        else:
            # Add character
            self.target_input.text += key
        
        Logger.debug(f"KeyboardWidget: Key pressed '{key}', current text: {self.target_input.text}")
