llmApp.directive('bsConnectionSelect', ['PythonService', 'ParamsHelperService','$stateParams', 'PLUGIN_PATHS', function (PythonService, ParamsHelperService,$stateParams,PLUGIN_PATHS) {
    return {
        restrict: 'E',
        scope: {
            config: '=',
            formName: '=', // Assuming formName needs to be binded to the parent scope for validation context.
            infoText: '@',
            labelText: '@',
            description: '@',
            configProperty: '@',
            context: '@',
            onSuccess: '&',
            onDatasetCreated: '&',
            fieldRequired:'='
        },
        templateUrl: PLUGIN_PATHS.WEBAPP +'bs-connection-select-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;
            //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
            let connectionBlurTimeout = null; // For managing blur event on connection input
            $scope.isNameInputFocused = false; // For ng-class styling on the dataset name input

            // Get project key from state params
            let projectKey = $stateParams.projectKey;


            $scope.initConnectionData = function () {

                let payload = {
                    parameterName: $scope.configProperty,
                    projectKey: projectKey
                };

                ParamsHelperService.do(payload, $scope.config, {}, {}).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);
                            });
                        });

                        if ($scope.config[$scope.configProperty]) {
                            var connectionName = $scope.config[$scope.configProperty];
                            var foundConnection = $scope.connections.find(function (d) {
                                return d.connectionName === connectionName;
                            });
                            if (foundConnection) {
                                $scope.selectedConnectionObj = foundConnection;
                                $scope.connectionFilter = foundConnection.connectionDisplayName; // Set input text
                            } else {
                                // If the configured dataset is no longer available, clear selection and config
                                $scope.config[$scope.configProperty] = null;
                                $scope.selectedConnectionObj = null;
                                $scope.connectionFilter = ''; // Clear input text
                            }
                        }
                    } else {

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

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

            let 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) {
                    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.config[$scope.configProperty] = connection.connectionName;
                $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
                $scope.config[$scope.configProperty] = null;
                // 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);
                }
            };

            //Handle input focus logic (open only if not already open)
            $scope.handleInputFocus = function () {
                if (!$scope.isConnectionDropdownOpen) {
                    $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
            };

            // 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));
            };


            $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();
        }]
    };
}]);
