"""
Compact Salesforce Dialog Implementation
========================================
Replaces the sprawling Salesforce tab with a compact, user-friendly dialog system.

Save this file as: C:/Users/Mikeh/Python/Fuzzy_Matcher/src/fmatch/desktop/gui_compact_sf.py

Performance Notes:
- Consider adding @functools.lru_cache(maxsize=64) to SalesforceIntegration.get_object_fields()
- Monitor memory usage with 50k+ row datasets (target < 400MB RSS)
"""

import tkinter as tk
from tkinter import ttk, messagebox
from typing import Optional, List, Callable
import threading
import asyncio
import logging
import pandas as pd

log = logging.getLogger(__name__)

# Salesforce imports - adjust based on where this file is saved
try:
    # If this file is in desktop folder
    from ..integrations.salesforce.core import SalesforceIntegration
    from ..integrations.salesforce.gui_integration import SalesforceConnectionDialog
except ImportError:
    # Fallback if imports fail
    SalesforceIntegration = None
    SalesforceConnectionDialog = None
    log.warning("Salesforce integration modules not found")

# UI Constants for compact tiles
COMPACT_TILE_HEIGHT = 50
COMPACT_TILE_WIDTH = 100


class CompactSalesforceDialog(tk.Toplevel):
    """
    Compact dialog for Salesforce object and field selection.
    Target size: 400x300 pixels
    """

    def __init__(self, parent, sf_integration, is_source: bool = True):
        super().__init__(parent)
        self.parent = parent
        self.sf_integration = sf_integration
        self.is_source = is_source

        # Dialog setup
        self.title("Salesforce Data Source")
        self.geometry("400x300")
        self.resizable(False, False)
        self.transient(parent)
        self.grab_set()

        # Variables
        self.status_var = tk.StringVar()
        self.object_var = tk.StringVar()
        self.limit_var = tk.StringVar(value="10,000")
        self.selected_fields = []
        self.available_objects = []
        self.current_object_fields = []

        # Build UI
        self._build_ui()
        self._center_window()

        # Check connection and load objects
        self._check_connection()

    def _build_ui(self):
        """Build the compact dialog UI."""
        main_frame = ttk.Frame(self, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # Status row
        status_frame = ttk.Frame(main_frame)
        status_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(status_frame, text="Status:").pack(side=tk.LEFT, padx=(0, 5))
        self.status_label = ttk.Label(status_frame, textvariable=self.status_var)
        self.status_label.pack(side=tk.LEFT)

        self.reconnect_btn = ttk.Button(
            status_frame,
            text="(reconnect?)",
            command=self._reconnect,
            style="Link.TButton",
        )
        self.reconnect_btn.pack(side=tk.LEFT, padx=(5, 0))
        self.reconnect_btn.pack_forget()  # Initially hidden

        # Object selection
        object_frame = ttk.Frame(main_frame)
        object_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(object_frame, text="Object:").pack(side=tk.LEFT, padx=(0, 10))
        self.object_combo = ttk.Combobox(
            object_frame, textvariable=self.object_var, state="readonly", width=25
        )
        self.object_combo.pack(side=tk.LEFT, fill=tk.X, expand=True)
        self.object_combo.bind("<<ComboboxSelected>>", self._on_object_selected)

        # Fields selection
        fields_frame = ttk.Frame(main_frame)
        fields_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(fields_frame, text="Fields:").pack(side=tk.LEFT, padx=(0, 10))

        # Multi-select field button
        self.fields_btn = ttk.Button(
            fields_frame, text="Select fields...", command=self._show_field_selector
        )
        self.fields_btn.pack(side=tk.LEFT, fill=tk.X, expand=True)

        # Limit selection
        limit_frame = ttk.Frame(main_frame)
        limit_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(limit_frame, text="Limit:").pack(side=tk.LEFT, padx=(0, 10))
        self.limit_combo = ttk.Combobox(
            limit_frame,
            textvariable=self.limit_var,
            values=["1,000", "5,000", "10,000", "25,000", "50,000"],
            state="readonly",
            width=10,
        )
        self.limit_combo.pack(side=tk.LEFT)

        # Progress indicator (initially hidden)
        self.progress_frame = ttk.Frame(main_frame)
        self.progress_bar = ttk.Progressbar(
            self.progress_frame,
            mode="indeterminate",
            length=200,
            style="Horizontal.TProgressbar",
        )
        self.progress_bar.pack()
        self.progress_label = ttk.Label(
            self.progress_frame, text="Loading data...", font=("TkDefaultFont", 9)
        )
        self.progress_label.pack()

        # Spacer to push buttons to bottom
        ttk.Frame(main_frame).pack(fill=tk.BOTH, expand=True)

        # Button row
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, side=tk.BOTTOM)

        ttk.Button(button_frame, text="Cancel", command=self.destroy).pack(
            side=tk.RIGHT, padx=(5, 0)
        )

        self.load_btn = ttk.Button(
            button_frame,
            text=f"Load as {'Source' if self.is_source else 'Reference'}",
            command=self._load_data,
            style="Primary.TButton",
            state=tk.DISABLED,
        )
        self.load_btn.pack(side=tk.RIGHT)

    def _check_connection(self):
        """Check Salesforce connection and load objects."""
        if not self.sf_integration or not self.sf_integration.is_connected():
            self.status_var.set("❌ Not connected")
            self.status_label.config(foreground="red")
            self.reconnect_btn.pack(side=tk.LEFT, padx=(5, 0))
            return

        self.status_var.set("✅ Connected")
        self.status_label.config(foreground="green")
        self.reconnect_btn.pack(side=tk.LEFT, padx=(5, 0))

        # Load objects asynchronously
        self._load_objects()

    def _reconnect(self):
        """Handle reconnection request."""
        # Store dialog state
        is_source = self.is_source
        parent = self.parent

        # Close current dialog
        self.destroy()

        # Show connection dialog
        if hasattr(parent, "_connect_to_salesforce"):
            parent._connect_to_salesforce()

            # Reopen this dialog after connection (if successful)
            if (
                hasattr(parent, "sf_integration")
                and parent.sf_integration
                and parent.sf_integration.is_connected()
            ):
                parent.after(
                    100,
                    lambda: CompactSalesforceDialog(
                        parent, parent.sf_integration, is_source
                    ),
                )

    def _load_objects(self):
        """Load available Salesforce objects."""
        self.object_combo["values"] = ["Loading..."]
        self.object_var.set("Loading...")

        def load_async():
            try:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                try:
                    objects = loop.run_until_complete(self.sf_integration.get_objects())
                finally:
                    loop.close()
                self.after(0, self._populate_objects, objects)

            except Exception as e:
                log.error(f"Error loading objects: {e}")
                self.after(0, self._show_error, f"Failed to load objects: {str(e)}")

        threading.Thread(target=load_async, daemon=True).start()

    def _populate_objects(self, objects):
        """Populate the objects dropdown."""
        self.available_objects = objects

        # Filter to common objects for better UX
        common_objects = ["Lead", "Account", "Contact", "Opportunity", "Case"]

        # Sort objects with common ones first
        object_names = []
        for name in common_objects:
            obj = next((o for o in objects if o.name == name), None)
            if obj and obj.queryable:
                object_names.append(obj.name)

        # Add remaining queryable objects
        for obj in sorted(objects, key=lambda x: x.label):
            if obj.queryable and obj.name not in object_names:
                object_names.append(obj.name)

        self.object_combo["values"] = object_names

        # Pre-select Lead if available
        if "Lead" in object_names:
            self.object_var.set("Lead")
            self._on_object_selected()
        elif object_names:
            self.object_var.set(object_names[0])
            self._on_object_selected()

    def _on_object_selected(self, event=None):
        """Handle object selection."""
        object_name = self.object_var.get()
        if not object_name or object_name == "Loading...":
            return

        # Reset fields
        self.selected_fields = []
        self.fields_btn.config(text="Loading fields...")

        # Load fields for selected object
        def load_fields_async():
            try:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                try:
                    fields = loop.run_until_complete(
                        self.sf_integration.get_object_fields(object_name)
                    )
                finally:
                    loop.close()
                self.after(0, self._populate_fields, fields)

            except Exception as e:
                log.error(f"Error loading fields: {e}")
                self.after(0, self._show_error, f"Failed to load fields: {str(e)}")

        threading.Thread(target=load_fields_async, daemon=True).start()

    def _populate_fields(self, fields):
        """Store fields and update UI."""
        self.current_object_fields = fields

        # Auto-select essential fields
        essential_fields = self._get_essential_fields()
        self.selected_fields = [
            f for f in essential_fields if f in [field.name for field in fields]
        ]

        self._update_fields_button()
        self.load_btn.config(state=tk.NORMAL)

    def _get_essential_fields(self):
        """Get essential fields based on object type."""
        object_name = self.object_var.get()

        # Common fields for all objects
        common = ["Id", "Name", "CreatedDate", "LastModifiedDate"]

        # Object-specific fields
        if object_name == "Lead":
            return common + ["Email", "Company", "Status"]
        elif object_name == "Account":
            return common + ["Website", "Type", "Industry"]
        elif object_name == "Contact":
            return common + ["Email", "AccountId", "Title"]
        elif object_name == "Opportunity":
            return common + ["Amount", "CloseDate", "StageName"]
        else:
            return common

    def _update_fields_button(self):
        """Update the fields button text."""
        count = len(self.selected_fields)
        if count == 0:
            self.fields_btn.config(text="Select fields...")
        else:
            # Show abbreviated list
            field_list = ", ".join(self.selected_fields[:3])
            if count > 3:
                field_list += f" +{count-3} more"
            self.fields_btn.config(text=f"[{field_list}] ▼")

    def _show_field_selector(self):
        """Show the advanced field selector dropdown."""
        selector = FieldSelectorDropdown(
            self,
            self.current_object_fields,
            self.selected_fields,
            self._on_fields_selected,
        )

    def _on_fields_selected(self, selected_fields):
        """Handle field selection update."""
        self.selected_fields = selected_fields
        self._update_fields_button()

    def _build_soql(self, object_name: str, fields: List[str], limit: int) -> str:
        """Build SOQL query. Exposed for testing."""
        fields_str = ", ".join(fields)
        return f"SELECT {fields_str} FROM {object_name} LIMIT {limit}"

    def _load_data(self):
        """Load data from Salesforce."""
        if not self.selected_fields:
            messagebox.showwarning("No Fields", "Please select at least one field")
            return

        # Disable UI during load
        self.load_btn.config(state=tk.DISABLED, text="Loading...")

        # Show progress indicator
        self.progress_frame.pack(fill=tk.X, pady=(10, 0), before=self.load_btn.master)
        self.progress_bar.start(10)  # Start animation

        # Build SOQL query
        object_name = self.object_var.get()
        limit = int(self.limit_var.get().replace(",", ""))  # Convert to int for safety
        soql = self._build_soql(object_name, self.selected_fields, limit)

        # Update progress label with details
        self.progress_label.config(text=f"Loading {limit:,} {object_name} records...")

        def load_data_async():
            try:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                try:
                    df = loop.run_until_complete(self.sf_integration.query_data(soql))
                finally:
                    loop.close()
                self.after(0, self._handle_data_loaded, df, object_name)

            except Exception as e:
                log.error(f"Error loading data: {e}")
                self.after(0, self._show_error, f"Failed to load data: {str(e)}")

        threading.Thread(target=load_data_async, daemon=True).start()

    def _handle_data_loaded(self, df: pd.DataFrame, object_name: str):
        """Handle loaded data."""
        # Hide progress indicator
        self.progress_bar.stop()
        self.progress_frame.pack_forget()

        if df is not None and not df.empty:
            # Call parent's handler
            if hasattr(self.parent, "_handle_salesforce_data_loaded"):
                self.parent._handle_salesforce_data_loaded(
                    df, self.is_source, object_name
                )
            self.destroy()
        else:
            self._show_error("No data returned from query")
            self.load_btn.config(
                state=tk.NORMAL,
                text=f"Load as {'Source' if self.is_source else 'Reference'}",
            )

    def _show_error(self, error_msg: str):
        """Show error message."""
        # Hide progress indicator if showing
        if hasattr(self, "progress_bar"):
            self.progress_bar.stop()
            self.progress_frame.pack_forget()

        messagebox.showerror("Error", error_msg)

    def _center_window(self):
        """Center dialog on parent window."""
        self.update_idletasks()
        x = (
            self.parent.winfo_x()
            + (self.parent.winfo_width() // 2)
            - (self.winfo_width() // 2)
        )
        y = (
            self.parent.winfo_y()
            + (self.parent.winfo_height() // 2)
            - (self.winfo_height() // 2)
        )
        self.geometry(f"+{x}+{y}")


class FieldSelectorDropdown(tk.Toplevel):
    """
    Advanced multi-select field selector dropdown.
    """

    def __init__(self, parent, fields, selected_fields, callback):
        super().__init__(parent)
        self.parent = parent
        self.fields = fields
        self.selected_fields = selected_fields.copy()
        self.callback = callback

        # Window setup
        self.title("")
        self.overrideredirect(True)  # Remove window decorations
        self.configure(bg="white", highlightbackground="gray", highlightthickness=1)

        # Variables
        self.check_vars = {}

        # Build UI
        self._build_ui()
        self._position_window()

        # Bind global click to close when clicking outside
        self.bind_id = self.parent.bind_all(
            "<Button-1>", self._check_click_outside, "+"
        )
        self.bind("<Destroy>", self._cleanup_bindings)

        self.focus_set()

    def _build_ui(self):
        """Build the dropdown UI."""
        main_frame = ttk.Frame(self, style="Dropdown.TFrame")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)

        # Header
        header_frame = ttk.Frame(main_frame)
        header_frame.pack(fill=tk.X, padx=5, pady=5)

        self.count_label = ttk.Label(
            header_frame, text=f"Select Fields ({len(self.selected_fields)} selected)"
        )
        self.count_label.pack(side=tk.LEFT)

        # Field list with scrollbar
        list_frame = ttk.Frame(main_frame)
        list_frame.pack(fill=tk.BOTH, expand=True, padx=5)

        # Canvas for scrolling
        canvas = tk.Canvas(
            list_frame, height=200, width=300, bg="white", highlightthickness=0
        )
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = ttk.Frame(canvas)

        scrollable_frame.bind(
            "<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        # Add checkboxes for fields
        for field in self.fields:
            var = tk.BooleanVar(value=field.name in self.selected_fields)
            self.check_vars[field.name] = var

            cb = ttk.Checkbutton(
                scrollable_frame,
                text=f"{field.name} ({field.type})",
                variable=var,
                command=self._update_selection,
            )
            cb.pack(anchor=tk.W, pady=2)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # Preset buttons
        preset_frame = ttk.Frame(main_frame)
        preset_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(preset_frame, text="Presets:").pack(side=tk.LEFT, padx=(0, 5))

        ttk.Button(preset_frame, text="Essential", command=self._select_essential).pack(
            side=tk.LEFT, padx=2
        )

        ttk.Button(preset_frame, text="All", command=self._select_all).pack(
            side=tk.LEFT, padx=2
        )

        ttk.Button(preset_frame, text="None", command=self._select_none).pack(
            side=tk.LEFT, padx=2
        )

        # Done button
        ttk.Button(main_frame, text="Done", command=self._done).pack(pady=5)

    def _position_window(self):
        """Position dropdown below the parent button."""
        self.update_idletasks()

        # Get parent button position
        x = self.parent.fields_btn.winfo_rootx()
        y = self.parent.fields_btn.winfo_rooty() + self.parent.fields_btn.winfo_height()

        self.geometry(f"+{x}+{y}")

    def _update_selection(self):
        """Update selection count."""
        count = sum(1 for var in self.check_vars.values() if var.get())
        self.count_label.config(text=f"Select Fields ({count} selected)")

    def _select_essential(self):
        """Select essential fields."""
        essential = self.parent._get_essential_fields()
        for field_name, var in self.check_vars.items():
            var.set(field_name in essential)
        self._update_selection()

    def _select_all(self):
        """Select all fields."""
        for var in self.check_vars.values():
            var.set(True)
        self._update_selection()

    def _select_none(self):
        """Clear selection."""
        for var in self.check_vars.values():
            var.set(False)
        self._update_selection()

    def _done(self):
        """Apply selection and close."""
        selected = [name for name, var in self.check_vars.items() if var.get()]
        self.callback(selected)
        self.destroy()

    def _check_click_outside(self, event):
        """Check if click was outside the dropdown."""
        try:
            widget = event.widget
            # Check if click was inside this window or its children
            if widget != self and widget not in self.winfo_children():
                # Check if widget is a child of any child frame
                parent = widget
                while parent:
                    if parent == self:
                        return
                    parent = parent.master if hasattr(parent, "master") else None

                # Click was outside - close dropdown
                self.destroy()
        except:
            pass

    def _cleanup_bindings(self, event=None):
        """Clean up global bindings on destroy."""
        try:
            self.parent.unbind_all("<Button-1>", self.bind_id)
        except:
            pass

    def _on_focus_out(self, event):
        """Fallback for focus out (kept for compatibility)."""
        if not self.winfo_containing(event.x_root, event.y_root):
            self.destroy()


class DataSourceTile(ttk.Frame):
    """
    Clickable tile widget for data source selection.
    """

    def __init__(
        self,
        parent,
        title: str,
        icon: str,
        status: str = "",
        command: Optional[Callable] = None,
        **kwargs,
    ):
        super().__init__(parent, **kwargs)
        self.title = title
        self.icon = icon
        self.status = status
        self.command = command
        self.is_connected = "Connected" in status

        # Configure style
        self.configure(relief="raised", borderwidth=1)

        # Build tile
        self._build_tile()

        # Bind click events
        self.bind("<Button-1>", self._on_click)
        for child in self.winfo_children():
            child.bind("<Button-1>", self._on_click)

        # Hover effects
        self.bind("<Enter>", self._on_enter)
        self.bind("<Leave>", self._on_leave)

    def _build_tile(self):
        """Build the tile UI."""
        # Main container with minimal padding
        container = ttk.Frame(self, padding="8")  # Reduced from 15
        container.pack(fill=tk.BOTH, expand=True)

        # Icon (using text for simplicity)
        icon_label = ttk.Label(container, text=self.icon, font=("TkDefaultFont", 24))
        icon_label.pack()

        # Title
        title_label = ttk.Label(
            container, text=self.title, font=("TkDefaultFont", 12, "bold")
        )
        title_label.pack(pady=(5, 0))

        # Status
        if self.status:
            status_color = "green" if self.is_connected else "gray"
            status_label = ttk.Label(
                container,
                text=self.status,
                font=("TkDefaultFont", 9),
                foreground=status_color,
            )
            status_label.pack()

        # Re-bind click events after rebuild
        self.bind("<Button-1>", self._on_click)
        for child in self.winfo_children():
            child.bind("<Button-1>", self._on_click)
            # ADD THIS: Bind to all descendants
            for subchild in child.winfo_children():
                subchild.bind("<Button-1>", self._on_click)

    def _on_click(self, event=None):
        """Handle tile click with guard against multiple simultaneous clicks."""
        print(f"DEBUG: Tile clicked - {self.title}")  # ADD THIS
        if self.command and not getattr(self, "_busy", False):
            print(f"DEBUG: Executing command for {self.title}")  # ADD THIS
            self._busy = True
            try:
                # Visual feedback
                self.configure(relief="sunken")
                self.update_idletasks()

                # Show busy cursor
                self.configure(cursor="watch")

                # Execute command
                self.command()
            except Exception as e:
                print(f"DEBUG: Error in tile command: {e}")  # ADD THIS
                import traceback

                traceback.print_exc()
            finally:
                # Reset state
                self._busy = False
                self.configure(relief="raised", cursor="")

    def _on_enter(self, event):
        """Handle mouse enter."""
        self.configure(relief="groove", borderwidth=2)
        self.configure(cursor="hand2")

    def _on_leave(self, event):
        """Handle mouse leave."""
        self.configure(relief="raised", borderwidth=1)
        self.configure(cursor="")

    def update_status(self, status: str):
        """Update the tile status."""
        self.status = status
        self.is_connected = "Connected" in status
        # Rebuild tile to update status
        for widget in self.winfo_children():
            widget.destroy()
        self._build_tile()


class DataSourcePicker(ttk.Frame):
    """
    Unified data source picker with tiles for Files and Salesforce.
    Replaces the current separate file loading buttons.
    """

    def __init__(self, parent, app):
        super().__init__(parent)
        self.app = app
        self._build_compact_data_picker()  # Make sure this is called!

    def _get_salesforce_status(self) -> str:
        """Helper to get the current Salesforce connection status."""
        if (
            hasattr(self.app, "sf_integration")
            and self.app.sf_integration
            and self.app.sf_integration.is_connected()
        ):
            return "✓ Connected"
        elif hasattr(self.app, "sf_integration") and self.app.sf_integration:
            return "Not connected"
        return ""

    def _build_compact_data_picker(self):
        """Modified DataSourcePicker._build_ui for compact tiles."""
        # Tiles container with minimal padding
        tiles_frame = ttk.Frame(self)
        tiles_frame.pack(fill=tk.X, expand=False, pady=0)  # Remove default padding

        # Compact tiles with fixed dimensions
        self.files_tile = DataSourceTile(
            tiles_frame, title="Files", icon="📁", status="", command=self._load_files
        )
        self.files_tile.configure(height=COMPACT_TILE_HEIGHT, width=COMPACT_TILE_WIDTH)
        self.files_tile.pack(side=tk.LEFT, padx=5)  # Remove fill and expand
        self.files_tile.pack_propagate(False)  # Critical! Honor fixed size

        sf_status = self._get_salesforce_status()

        self.salesforce_tile = DataSourceTile(
            tiles_frame,
            title="Salesforce",
            icon="☁️",
            status=sf_status,
            command=self._load_salesforce,
        )
        self.salesforce_tile.configure(
            height=COMPACT_TILE_HEIGHT, width=COMPACT_TILE_WIDTH
        )
        self.salesforce_tile.pack(side=tk.LEFT, padx=5)  # Remove fill and expand
        self.salesforce_tile.pack_propagate(False)  # Critical! Honor fixed size

    def _load_files(self):
        """Handle file loading with role selection."""
        print("DEBUG: DataSourcePicker._load_files called")

        # Check if we need to ask for role
        role = self.app._ask_role_if_needed()
        if role is None:  # User cancelled
            return

        print(f"DEBUG: Loading file as {'source' if role else 'reference'}")
        self.app.browse_file(is_source=role)

    def _load_salesforce(self):
        """Handle Salesforce loading with role selection."""
        print("DEBUG: DataSourcePicker._load_salesforce called")

        # Check if connected
        if not hasattr(self.app, "sf_integration") or not self.app.sf_integration:
            # Show connection dialog first
            if hasattr(self.app, "_connect_to_salesforce"):
                self.app._connect_to_salesforce()
            return

        # Check if token is still valid
        if not self.app.sf_integration.is_connected():
            # Update tile to show disconnected
            self.salesforce_tile.update_status("Token expired")
            # Show connection dialog
            if hasattr(self.app, "_connect_to_salesforce"):
                self.app._connect_to_salesforce()
            return

        # Check if we need to ask for role
        role = self.app._ask_role_if_needed()
        if role is None:  # User cancelled
            return

        print(f"DEBUG: Loading Salesforce as {'source' if role else 'reference'}")
        dialog = CompactSalesforceDialog(
            self.app, self.app.sf_integration, is_source=role
        )

    def update_salesforce_status(self):
        """Update Salesforce tile status."""
        if hasattr(self.app, "sf_integration") and self.app.sf_integration:
            if self.app.sf_integration.is_connected():
                self.salesforce_tile.update_status("✓ Connected")
            else:
                self.salesforce_tile.update_status("Not connected")
        else:
            self.salesforce_tile.update_status("")


# Integration helper functions


def integrate_compact_salesforce(app):
    """
    Integration instructions for adding the compact Salesforce dialog to the main app.

    In your FuzzyMatcherApp class:

    1. Replace the current file loading buttons with DataSourcePicker:

       # In _build_input_section() or where file buttons are created:
       # Remove:
       # - btn_src_browse
       # - btn_ref_browse

       # Add:
       self.data_source_picker = DataSourcePicker(input_frame, self)
       self.data_source_picker.pack(fill=tk.X, pady=10)

    2. Add method to handle Salesforce connection:

       def _connect_to_salesforce(self):
           from .gui_integration import SalesforceConnectionDialog
           dialog = SalesforceConnectionDialog(self, self.sf_credentials)
           self.wait_window(dialog)

           if dialog.result:
               self.sf_credentials = dialog.result
               self.sf_integration = SalesforceIntegration(self.sf_credentials)

               # Update data source picker
               if hasattr(self, 'data_source_picker'):
                   self.data_source_picker.update_salesforce_status()

    3. Ensure _handle_salesforce_data_loaded() exists (already in your code)

    4. Update refresh_ui() to update the data source picker:

       if hasattr(self, 'data_source_picker'):
           self.data_source_picker.update_salesforce_status()
    """
    pass


# Style configuration for modern look


def configure_compact_styles(root_window=None):
    """Configure custom styles for the compact dialog."""
    style = ttk.Style(root_window) if root_window else ttk.Style()

    # Link button style (for reconnect)
    style.configure("Link.TButton", relief="flat", borderwidth=0, foreground="blue")

    # Dropdown frame style
    style.configure(
        "Dropdown.TFrame", background="white", borderwidth=1, relief="solid"
    )

    # Primary button style
    style.configure("Primary.TButton", foreground="white", background="#007bff")

    return style
