llmApp.directive('bsConnectionCreate', ['PythonService', 'SharedPromiseService','PLUGIN_PATHS', function (PythonService, SharedPromiseService,PLUGIN_PATHS) {
    return {
        restrict: 'E',
        scope: {
            config: '=',
            formName: '@', // Assuming formName needs to be binded to the parent scope for validation context.
            infoText: '@',
            labelText: '@',
            configProperty: '@',
            context: '@',
            onSuccess: '&',
            onDatasetCreated: '&'
        },
        templateUrl: PLUGIN_PATHS.WEBAPP +'bs-connection-create-template.html', // Corrected path based on context example
        controller: ['$scope', '$timeout', '$element', function ($scope, $timeout, $element) {
            $scope.isConnectionDropdownOpen = false;
            $scope.isDropdownHovered = false;
            $scope.connectionFilter = ''; // Model for the main connection input field
            $scope.connections = [];
            $scope.connectionsByType = {};
            $scope.selectedConnectionObj = null;
            $scope.datasetNameInput = ''; // From createDataset functionality
            $scope.showTooltip = false;


            //Flag to control when filtering is applied (starts false to show all on open)
            $scope.filterActive = false;

            $scope.isConnectionFocused = false; // For ng-class styling on the connection input
            var connectionBlurTimeout = null; // For managing blur event on connection input
            $scope.isNameInputFocused = false; // For ng-class styling on the dataset name input

            $scope.initConnectionData = function () {

                SharedPromiseService.getData('connection_selector').then(function (data) {
                    if (data && data.choices) {
                        $scope.connectionsByType = {};
                        $scope.connections = [];
                        Object.keys(data.choices).forEach(function (connType) {
                            $scope.connectionsByType[connType] = [];
                            data.choices[connType].forEach(function (connName) {
                                var connection = {
                                    id: connName,
                                    connectionName: connName,
                                    connectionDisplayName: connName,
                                    connectionType: connType,
                                    isHovered: false
                                };
                                $scope.connections.push(connection);
                                $scope.connectionsByType[connType].push(connection);
                            });
                        });

                        // Set initial selected connection and filter value
                        // If config[$scope.configProperty] is set elsewhere, and it maps to a connection, that should take precedence
                        // For now, handling default selection if no previous config is loaded.
                        if ($scope.connections.length > 0) {
                            if (!$scope.selectedConnectionObj) { // Avoid overwriting if already set by config or previous interaction
                                $scope.selectedConnectionObj = $scope.connections[0];
                                $scope.connectionFilter = $scope.selectedConnectionObj.connectionDisplayName;

                            } else {
                                // If a connection was already selected (e.g., from config binding)
                                // ensure the input field reflects it, in case it differs from the current connectionFilter.
                                // This handles cases where the initial data fetch might be slower and selectedConnectionObj is already set.
                                if (!$scope.connectionFilter || $scope.connectionFilter !== $scope.selectedConnectionObj.connectionDisplayName) {
                                    $scope.connectionFilter = $scope.selectedConnectionObj.connectionDisplayName;
                                }
                            }
                        } else {
                            // No connections available
                            $scope.selectedConnectionObj = null;
                            $scope.connectionFilter = '';
                        }

                    } else {

                        $scope.connections = [];
                        $scope.connectionsByType = {};
                    }
                }, function (error) {

                    $scope.connections = [];
                    $scope.connectionsByType = {};
                });
            };

            var connectionDocumentClickHandler = function (event) {
                // Check if click is outside the connection selector element
                if ($scope.isConnectionDropdownOpen && !$element[0].contains(event.target)) {
                    $scope.$apply(function () {
                        $scope.closeConnectionDropdownAndRevertText();
                    });
                }
            };

            $scope.closeConnectionDropdownAndRevertText = function () {
                $scope.isConnectionDropdownOpen = false;
                $scope.isConnectionFocused = false; // Also reset focused state when closing
                angular.element(document).off('click', connectionDocumentClickHandler);
                if ($scope.selectedConnectionObj) {
                    // Revert input to the display name of the selected connection
                    $scope.connectionFilter = $scope.selectedConnectionObj.connectionDisplayName;
                } else {
                    //$scope.connectionFilter = ''; // Optionally clear if no valid selection on blur
                }
                //Reset filterActive on close
                $scope.filterActive = false;
            };

            $scope.openConnectionDropdown = function (clearFilterOnOpen) {
                if (connectionBlurTimeout) $timeout.cancel(connectionBlurTimeout);
                if($scope.isConnectionDropdownOpen){
                    $scope.closeConnectionDropdownAndRevertText();
                }
                else{
                    if (clearFilterOnOpen) {
                        // Clear the filter input when opened via the arrow click
                        $scope.connectionFilter = '';
                    }

                    $scope.isConnectionDropdownOpen = true;
                    //Disable filtering initially (show all, even if datasetFilter has text)
                    $scope.filterActive = false;
                    $timeout(function () {
                        // Add click listener to close dropdown when clicking outside
                        angular.element(document).on('click', connectionDocumentClickHandler);
                    }, 0);
                }
            };

            $scope.selectConnection = function (connection) {
                if (connectionBlurTimeout) $timeout.cancel(connectionBlurTimeout);

                $scope.selectedConnectionObj = connection;
                $scope.connectionFilter = connection.connectionDisplayName; // Update input field text
                $scope.isConnectionDropdownOpen = false;
                $scope.isConnectionFocused = false; // Reset focus when selection is made
                angular.element(document).off('click', connectionDocumentClickHandler);
            };

            // Renamed from clearConnectionFilter to clearConnectionSelection for clarity
            $scope.clearConnectionSelection = function () {
                $scope.connectionFilter = ''; // Clear the input
                $scope.selectedConnectionObj = null; // Deselect
                // Optionally reopen the dropdown to allow selection of another connection
                $scope.openConnectionDropdown(true); // Open with clear filter
                // Optionally focus the input after clearing/reopening
                $element[0].querySelector('input[ng-model="connectionFilter"]').focus();
            };

            $scope.handleConnectionInputChange = function () {
                // Deselect if the typed text doesn't match the selected connection's display name
                if ($scope.selectedConnectionObj && $scope.connectionFilter !== $scope.selectedConnectionObj.connectionDisplayName) {
                    $scope.selectedConnectionObj = null;
                    //$scope.config[$scope.configProperty] = null; // If selection is required
                }

                //Activate filtering now that the user is typing
                $scope.filterActive = true;
                // Automatically open dropdown if not already open and user is typing
                if (!$scope.isConnectionDropdownOpen && $scope.connectionFilter) {
                    // Pass false to not clear filter, just open for filtering
                    $scope.openConnectionDropdown(false);
                }
            };

            $scope.handleConnectionInputBlur = function () {
                // Use timeout to allow click events on dropdown items to be processed before closing
                connectionBlurTimeout = $timeout(function () {
                    // If dropdown is still open (e.g. tabbed away from input)
                    if ($scope.isConnectionDropdownOpen) {
                        $scope.closeConnectionDropdownAndRevertText();
                    }
                }, 200); // Delay for UX
            };

            //Handle input focus logic (open only if not already open)
            $scope.handleInputFocus = function () {
                if (!$scope.isConnectionDropdownOpen) {
                    $scope.openConnectionDropdown(false);
                }
            };

            // Filtering logic (uses $scope.connectionFilter)
            //Filter depending on the type and value of the connection
            $scope.connectionMatchesFilter = function (connection) {
                //If filter not active, show all
                if (!$scope.filterActive) return true;
                if (!$scope.connectionFilter) return true;
                const filter = $scope.connectionFilter.toLowerCase();
                return connection.connectionDisplayName.toLowerCase().includes(filter) || connection.connectionType.toLowerCase().includes(filter);
            };

            $scope.typeHasMatchingConnections = function (type) {
                if (!$scope.connectionsByType[type]) return false;
                return $scope.connectionsByType[type].some(c => $scope.connectionMatchesFilter(c));
            };

            $scope.hasMatchingConnections = function () {
                if ($scope.connections.length === 0) return false;
                if (!$scope.connectionFilter) return true; // If no filter text, all connections match
                return $scope.connections.some(c => $scope.connectionMatchesFilter(c));
            };

            // Create dataset function - no changes needed here as it uses other scope variables
            $scope.createDataset = function () {
                if (!$scope.datasetNameInput || !$scope.selectedConnectionObj) {
                    return;
                }
                PythonService.callPythonDo({
                    parameterName: 'create_dataset', arguments: {
                        name: $scope.datasetNameInput, connection: $scope.selectedConnectionObj
                    }
                }).then(function (response) {
                    if (response.success) {
                        // Update config with the newly created dataset name
                        $scope.config[$scope.configProperty] = response.dataset.datasetName;
                        $scope.datasetNameInput = ''; // Clear input for next potential creation

                        // --- BROADCAST THE EVENT ---
                        $scope.$emit('datasetCreated'); // EMITTING UPWARDS

                        $timeout(function () {
                            // Execute callbacks
                            if ($scope.onDatasetCreated) {
                                $scope.onDatasetCreated();
                            }

                            if ($scope.onSuccess) {
                                $scope.onSuccess({
                                    dataset: response.dataset, property: $scope.configProperty
                                });
                            }
                        });

                    } else {

                        // TODO: Add a notification modal to show the error
                    }
                });
            };


            $scope.resetForm = function () {
                $scope.datasetNameInput = '';
                $scope.selectedConnectionObj = null; // Clear selection upon full reset
                $scope.connectionFilter = '';
                // Ensure dropdown and focus are off
                $scope.isConnectionDropdownOpen = false;
                $scope.isConnectionFocused = false;
                $scope.isNameInputFocused = false;
                angular.element(document).off('click', connectionDocumentClickHandler);
            };

            // Cleanup listener and reset form elements when scope is destroyed
            $scope.$on('$destroy', function () {
                $scope.resetForm();
                // Ensure listener is detached if destroy happens while dropdown is open
                angular.element(document).off('click', connectionDocumentClickHandler);
            });

            // Initial data load
            $scope.initConnectionData();
        }]
    };
}]);
