"""
Help tab component for the Excel Filter GUI
"""

import tkinter as tk
from tkinter import ttk
import tkinter.font as tkfont


class HelpTab:
    """
    Help tab component that shows documentation and usage information
    """

    def __init__(self, parent_frame, win11_colors, scale_factor=1.0, translations=None, switch_language_callback=None):
        """
        Initialize the help tab

        Args:
            parent_frame: Parent frame to attach to
            win11_colors: Windows 11 color palette dictionary
            scale_factor: DPI scaling factor for high-resolution displays
            translations: Translations object for internationalization
            switch_language_callback: Callback function to switch language
        """
        self.frame = ttk.Frame(parent_frame)
        self.win11_colors = win11_colors
        self.scale_factor = scale_factor
        self.translations = translations
        self.switch_language_callback = switch_language_callback

        self.create_widgets()
    
    def create_widgets(self):
        """
        Create all widgets for the help tab
        """
        # Scale factors for DPI-aware sizing - ensure minimum text size of 12
        scaled_padding = int(10 * self.scale_factor)
        scaled_text_padding = int(12 * self.scale_factor)
        scaled_pack_padding = int(2 * self.scale_factor)
        scaled_font_size = max(int(10 * self.scale_factor), 12)

        # Main container
        help_main_frame = ttk.Frame(self.frame)
        help_main_frame.pack(fill=tk.BOTH, expand=True, padx=scaled_padding, pady=scaled_padding)

        # Language selector at the top of help tab
        if self.translations:
            language_frame = ttk.Frame(help_main_frame)
            language_frame.pack(fill=tk.X, pady=(0, scaled_padding))

            # Language selector label
            language_label = ttk.Label(language_frame, text=self.translations["language"])
            language_label.pack(side=tk.LEFT, padx=(0, int(5 * self.scale_factor)))

            # Frame for flag buttons
            flags_frame = ttk.Frame(language_frame)
            flags_frame.pack(side=tk.LEFT, padx=5)

            # German flag button
            german_button = ttk.Button(
                flags_frame,
                text="🇩🇪 German",
                command=lambda: self.switch_language('de'),
                style='TButton'
            )
            german_button.pack(side=tk.LEFT, padx=(0, 5))

            # English flag button
            english_button = ttk.Button(
                flags_frame,
                text="🇺🇸 English",
                command=lambda: self.switch_language('en'),
                style='TButton'
            )
            english_button.pack(side=tk.LEFT)

            # Highlight current language
            if self.translations.current_language == 'de':
                german_button.config(style='Primary.TButton')
            else:
                english_button.config(style='Primary.TButton')

        # Scrollbar for help content
        help_scrollbar = ttk.Scrollbar(help_main_frame)
        help_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # Help text with scrollbar - Windows 11 Fluent Design
        help_text_widget = tk.Text(help_main_frame, wrap=tk.WORD,
                                  bg=self.win11_colors['surface'],
                                  fg=self.win11_colors['text'],
                                  font=('Segoe UI', scaled_font_size) if 'Segoe UI' in tkfont.families() else ('Helvetica', scaled_font_size),
                                  borderwidth=1, relief="solid", padx=scaled_text_padding, pady=scaled_text_padding,
                                  selectbackground=self.win11_colors['primary'],
                                  selectforeground='white',
                                  yscrollcommand=help_scrollbar.set)
        help_text_widget.pack(fill=tk.BOTH, expand=True, padx=scaled_pack_padding, pady=scaled_pack_padding)
        help_scrollbar.config(command=help_text_widget.yview)
        
        # Configure scrollbar with Windows 11 styling
        style = ttk.Style()
        style.configure('TScrollbar', 
                       background=self.win11_colors['border'],
                       troughcolor=self.win11_colors['surface'],
                       bordercolor=self.win11_colors['border'],
                       arrowcolor=self.win11_colors['text'])
        
        # Help content from translations
        help_content = self.translations.get("help_content", "Help content not available")
        
        help_text_widget.insert(tk.END, help_content)
        help_text_widget.config(state=tk.DISABLED)
    
    def switch_language(self, new_language):
        """
        Switch the application language and update help content

        Args:
            new_language: New language code ('en' or 'de')
        """
        if self.switch_language_callback:
            self.switch_language_callback(new_language)

            # Update help content after language change
            self.update_help_content()

            # Update button styles to reflect current language
            self.update_button_styles()

    def update_help_content(self):
        """
        Update the help content text when language changes
        """
        # Find the help text widget and update its content
        for child in self.frame.winfo_children():
            if isinstance(child, ttk.Frame):
                for subchild in child.winfo_children():
                    if isinstance(subchild, tk.Text):
                        # Clear existing content and insert new translated content
                        subchild.config(state=tk.NORMAL)
                        subchild.delete(1.0, tk.END)
                        subchild.insert(tk.END, self.translations.get("help_content", "Help content not available"))
                        subchild.config(state=tk.DISABLED)
                        break

    def update_button_styles(self):
        """
        Update the language button styles to reflect the current language
        """
        # Find the language buttons and update their styles
        for child in self.frame.winfo_children():
            if isinstance(child, ttk.Frame):
                for subchild in child.winfo_children():
                    if isinstance(subchild, ttk.Frame):
                        for widget in subchild.winfo_children():
                            if isinstance(widget, ttk.Frame):
                                for button in widget.winfo_children():
                                    if isinstance(button, ttk.Button):
                                        if "German" in button.cget("text"):
                                            if self.translations.current_language == 'de':
                                                button.config(style='Primary.TButton')
                                            else:
                                                button.config(style='TButton')
                                        elif "English" in button.cget("text"):
                                            if self.translations.current_language == 'en':
                                                button.config(style='Primary.TButton')
                                            else:
                                                button.config(style='TButton')

    def get_frame(self):
        """
        Get the frame for this tab

        Returns:
            The frame containing all widgets
        """
        return self.frame
