"""
Main window component for the Excel Filter GUI
"""

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


class MainWindow:
    """
    Main window component that handles the overall GUI structure
    """
    
    def __init__(self, root):
        """
        Initialize the main window
        
        Args:
            root: Tkinter root window
        """
        self.root = root
        self.root.title("Excel Filter Tool")
        self.root.geometry("1200x700")
        self.root.resizable(True, True)

        # Windows 11 specific: Enable modern window styling and DPI awareness first
        self.scale_factor = 1.0
        try:
            import ctypes
            import sys
            if sys.platform == 'win32':
                try:
                    # Set DPI awareness for sharp rendering on high-DPI displays
                    try:
                        ctypes.windll.shcore.SetProcessDpiAwareness(2)  # PROCESS_PER_MONITOR_DPI_AWARE
                    except:
                        try:
                            ctypes.windll.shcore.SetProcessDpiAwareness(1)  # PROCESS_SYSTEM_DPI_AWARE
                        except:
                            ctypes.windll.user32.SetProcessDPIAware()

                    # Set Tkinter scaling to match system DPI for proper element sizes
                    try:
                        hdc = ctypes.windll.user32.GetDC(0)
                        dpi_x = ctypes.windll.gdi32.GetDeviceCaps(hdc, 88)  # LOGPIXELSX
                        ctypes.windll.user32.ReleaseDC(0, hdc)
                        self.scale_factor = dpi_x / 96.0  # 96 DPI = 100% scaling
                        self.root.tk.call('tk', 'scaling', self.scale_factor)
                    except:
                        pass  # If scaling setup fails, continue without it

                    # Enable dark mode for title bar
                    ctypes.windll.dwmapi.DwmSetWindowAttribute(
                        self.root.winfo_id(),
                        20,
                        ctypes.c_int(2),
                        ctypes.sizeof(ctypes.c_int)
                    )
                except:
                    pass  # If DPI awareness or DwmSetWindowAttribute fails, continue without it
        except:
            pass  # If ctypes import fails, continue without it

        # Windows 11 Design
        self.root.configure(bg='#f0f0f0')

        # Font configuration - ensure minimum size of 12
        try:
            base_font_size = max(int(10 * self.scale_factor), 12)
            self.default_font = ('Segoe UI', base_font_size) if 'Segoe UI' in tkfont.families() else ('Helvetica', base_font_size)
        except:
            self.default_font = ('Helvetica', 12)

        # Windows 11 Color palette
        self.win11_primary = '#0078d4'  # Windows 11 Blue
        self.win11_light = '#f0f0f0'   # Light gray
        self.win11_dark = '#e0e0e0'    # Dark gray
        self.win11_accent = '#005a9e'  # Accent color

        # Create main frame with minimal padding - tabs right at the top
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=0, pady=0)

        # Create notebook for tabs with Windows 11 styling - right at the top
        self.notebook = ttk.Notebook(self.main_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=0, pady=0)

        # Configure notebook padding and spacing for Windows 11 look
        style = ttk.Style()
        style.layout('TNotebook.Tab', [
            ('Notebook.tab', {
                'sticky': 'nswe',
                'children': [
                    ('Notebook.padding', {
                        'side': 'top',
                        'children': [
                            ('Notebook.label', {'side': 'top', 'sticky': ''})
                        ]
                    })
                ]
            })
        ])

        # Set window icon and other Windows 11 properties
        try:
            self.root.iconbitmap('app_icon.ico')  # Windows 11 style icon
        except:
            pass  # Icon not found, continue without it

        # Windows 11 window properties
        self.root.attributes('-alpha', 1.0)  # Ensure full opacity

        # Add Windows 11 style window controls (minimize, maximize, close)
        # This is handled automatically by Windows for Tkinter windows

        # Set window minimum size for better usability (larger minimum to accommodate the bigger interface)
        min_width = int(1200 * self.scale_factor)
        min_height = int(700 * self.scale_factor)
        self.root.minsize(min_width, min_height)

        self.root.update()

        # Configure styles
        self.configure_styles()
    
    def configure_styles(self):
        """
        Configure Tkinter styles for Windows 11 Fluent Design look
        """
        style = ttk.Style()

        # Use clam theme for better appearance
        style.theme_use('clam')

        # Scale factors for DPI-aware sizing - ensure minimum size of 12
        font_size_normal = max(int(10 * self.scale_factor), 12)
        font_size_bold = max(int(10 * self.scale_factor), 12)
        font_size_heading = max(int(12 * self.scale_factor), 12)
        tab_padding = [int(16 * self.scale_factor), int(8 * self.scale_factor)]
        button_padding = (int(12 * self.scale_factor), int(6 * self.scale_factor))
        primary_button_padding = (int(16 * self.scale_factor), int(8 * self.scale_factor))
        entry_padding = int(10 * self.scale_factor)
        combobox_padding = int(8 * self.scale_factor)
        notebook_padding = [int(10 * self.scale_factor), int(5 * self.scale_factor)]

        # Windows 11 Fluent Design color palette
        win11_primary = '#0078d4'  # Windows 11 Blue
        win11_primary_dark = '#005a9e'  # Darker blue for hover effects
        win11_primary_light = '#cce4f7'  # Light blue for active states
        win11_background = '#f0f0f0'  # Light gray background
        win11_surface = '#ffffff'  # White surface
        win11_text = '#212121'  # Dark text
        win11_text_secondary = '#616161'  # Secondary text
        win11_border = '#e0e0e0'  # Border color
        win11_hover = '#e8f0fe'  # Hover effect
        win11_pressed = '#d0e0f5'  # Pressed effect

        # Tab styling - Windows 11 Fluent Design style
        style.configure('TNotebook', background=win11_background, borderwidth=1, relief='solid')
        style.configure('TNotebook.Tab',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       padding=tab_padding,
                       background=win11_background,
                       foreground=win11_text,
                       borderwidth=0,
                       relief='flat')
        style.map('TNotebook.Tab',
                 background=[("selected", win11_surface), ("active", win11_hover), ("!selected", win11_background)],
                 foreground=[("selected", win11_primary), ("!selected", win11_text_secondary)],
                 relief=[("selected", 'flat'), ("active", 'flat'), ("!selected", 'flat')])

        # Configure notebook padding and spacing
        style.configure('TNotebook', tabposition='n', padding=notebook_padding)

        # Button styling - Windows 11 Fluent Design
        style.configure('TButton',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       padding=button_padding,
                       borderwidth=1,
                       focuscolor=win11_primary,
                       background=win11_surface,
                       foreground=win11_text,
                       bordercolor=win11_border,
                       relief='flat')
        style.map('TButton',
                 foreground=[('active', win11_text), ('disabled', win11_text_secondary)],
                 background=[('active', win11_hover), ('pressed', win11_pressed), ('disabled', win11_background)],
                 bordercolor=[('active', win11_primary), ('pressed', win11_primary_dark)],
                 lightcolor=[('active', win11_hover)],
                 darkcolor=[('active', win11_pressed)])

        # Primary button style (for important actions)
        style.configure('Primary.TButton',
                       font=('Segoe UI', font_size_bold, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_bold, 'bold'),
                       padding=primary_button_padding,
                       background=win11_primary,
                       foreground=win11_surface,
                       borderwidth=0,
                       focuscolor=win11_primary_dark)
        style.map('Primary.TButton',
                 background=[('active', win11_primary_dark), ('pressed', win11_primary_dark), ('disabled', win11_background)],
                 foreground=[('active', win11_surface), ('pressed', win11_surface), ('disabled', win11_text_secondary)])

        # Entry field styling - Windows 11 style
        style.configure('TEntry',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       padding=entry_padding,
                       fieldbackground=win11_surface,
                       borderwidth=1,
                       relief='solid',
                       bordercolor=win11_border,
                       foreground=win11_text)
        style.map('TEntry',
                 fieldbackground=[('focus', win11_surface), ('readonly', win11_background)],
                 bordercolor=[('focus', win11_primary), ('readonly', win11_border)])

        # Label styling - Windows 11 style
        style.configure('TLabel',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       background=win11_background,
                       foreground=win11_text)

        # Heading label style
        style.configure('Heading.TLabel',
                       font=('Segoe UI', font_size_heading, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_heading, 'bold'),
                       background=win11_background,
                       foreground=win11_primary)

        # Frame styling
        style.configure('TFrame', background=win11_background)
        style.configure('TLabelframe',
                       font=('Segoe UI', font_size_bold, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_bold, 'bold'),
                       background=win11_background,
                       borderwidth=1,
                       relief='groove',
                       bordercolor=win11_border)
        style.configure('TLabelframe.Label',
                       font=('Segoe UI', font_size_bold, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_bold, 'bold'),
                       foreground=win11_primary,
                       background=win11_background)

        # Checkbutton styling
        style.configure('TCheckbutton',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       background=win11_background,
                       foreground=win11_text)
        style.map('TCheckbutton',
                 background=[('active', win11_hover), ('selected', win11_background)],
                 foreground=[('active', win11_text), ('selected', win11_text)])

        # Combobox styling
        style.configure('TCombobox',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       padding=combobox_padding,
                       fieldbackground=win11_surface,
                       borderwidth=1,
                       relief='solid',
                       bordercolor=win11_border,
                       foreground=win11_text)
        style.map('TCombobox',
                 fieldbackground=[('focus', win11_surface), ('readonly', win11_background)],
                 bordercolor=[('focus', win11_primary), ('readonly', win11_border)])

        # Scrollbar styling
        style.configure('TScrollbar',
                       background=win11_background,
                       troughcolor=win11_background,
                       bordercolor=win11_border,
                       arrowcolor=win11_text)
        style.map('TScrollbar',
                 background=[('active', win11_border), ('disabled', win11_background)],
                 troughcolor=[('active', win11_hover), ('disabled', win11_background)])

        # Treeview styling
        style.configure('Treeview',
                       font=('Segoe UI', font_size_normal, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', font_size_normal, 'normal'),
                       background=win11_surface,
                       foreground=win11_text,
                       fieldbackground=win11_surface,
                       bordercolor=win11_border)
        style.map('Treeview',
                 background=[('selected', win11_primary_light)],
                 foreground=[('selected', win11_text)])

        # Progressbar styling
        style.configure('TProgressbar',
                       background=win11_primary,
                       troughcolor=win11_background,
                       bordercolor=win11_border)
    
    def add_tab(self, tab_frame, text):
        """
        Add a tab to the notebook with Windows 11 styling

        Args:
            tab_frame: Frame to add as tab
            text: Tab title

        Returns:
            The added tab frame
        """
        # Add the tab with Windows 11 styling
        self.notebook.add(tab_frame, text=text)

        # Apply Windows 11 specific styling to the tab
        style = ttk.Style()

        # Get the tab index
        tab_index = len(self.notebook.tabs()) - 1
        tab_id = self.notebook.tabs()[tab_index]

        # Configure the tab to have Windows 11 appearance with scaled padding
        scaled_tab_padding = [int(16 * self.scale_factor), int(8 * self.scale_factor)]
        self.notebook.tab(tab_id, padding=scaled_tab_padding)

        return tab_frame
    
    def enhance_tab_appearance(self):
        """
        Enhance tab appearance to look more like Windows 11
        This should be called after all tabs are added
        """
        style = ttk.Style()

        # Windows 11 specific: Make tabs look more modern
        style.configure('TNotebook.Tab',
                       borderwidth=0,
                       focuscolor='#0078d4',
                       lightcolor='#f0f0f0',
                       darkcolor='#f0f0f0')

        # Add a subtle border to the notebook itself
        try:
            self.notebook.configure(borderwidth=1, relief='solid')
        except:
            pass  # Some Tkinter versions don't support borderwidth for notebooks

        # Configure the notebook background to match Windows 11
        style.configure('TNotebook',
                       background='#f0f0f0',
                       borderwidth=1,
                       relief='solid',
                       bordercolor='#e0e0e0')

        # Windows 11 specific: Add hover and selection effects
        style.map('TNotebook.Tab',
                 background=[('selected', '#ffffff'),
                            ('active', '#e8f0fe'),
                            ('!selected', '#f0f0f0')],
                 foreground=[('selected', '#0078d4'),
                            ('!selected', '#616161')])

        # Windows 11 specific: Make selected tab more prominent with scaled values
        scaled_tab_padding = [int(16 * self.scale_factor), int(8 * self.scale_factor)]
        scaled_font_size = int(10 * self.scale_factor)
        style.configure('TNotebook.Tab',
                       padding=scaled_tab_padding,
                       font=('Segoe UI', scaled_font_size, 'normal') if 'Segoe UI' in tkfont.families() else ('Helvetica', scaled_font_size, 'normal'))
    
    def run(self):
        """
        Run the main application loop
        """
        self.root.mainloop()
