import * as i0 from '@angular/core';
import { input, signal, viewChild, inject, effect, HostBinding, ChangeDetectionStrategy, Component } from '@angular/core';
import * as i1 from '@angular/forms';
import { Validators, NgControl, FormsModule } from '@angular/forms';
import * as i2 from 'primeng/autocomplete';
import { AutoCompleteModule } from 'primeng/autocomplete';
import * as i4 from 'primeng/inputgroup';
import { InputGroupModule } from 'primeng/inputgroup';
import * as i5 from 'primeng/inputgroupaddon';
import { InputGroupAddonModule } from 'primeng/inputgroupaddon';
import { Tooltip } from '@masterteam/components/tooltip';
import { FieldValidation } from '@masterteam/components/field-validation';
import { isInvalid } from '@masterteam/components';
import { Icon } from '@masterteam/icons';
import { Subject, distinctUntilChanged, tap, switchMap, of, finalize, catchError } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Avatar } from '@masterteam/components/avatar';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import * as i3 from 'primeng/api';

class UserSearchField {
    hint = input(...(ngDevMode ? [undefined, { debugName: "hint" }] : []));
    label = input(...(ngDevMode ? [undefined, { debugName: "label" }] : []));
    placeholder = input(...(ngDevMode ? [undefined, { debugName: "placeholder" }] : []));
    class = input('', ...(ngDevMode ? [{ debugName: "class" }] : []));
    readonly = input(false, ...(ngDevMode ? [{ debugName: "readonly" }] : []));
    required = input(false, ...(ngDevMode ? [{ debugName: "required" }] : []));
    apiUrl = input.required(...(ngDevMode ? [{ debugName: "apiUrl" }] : []));
    dataKey = input('data', ...(ngDevMode ? [{ debugName: "dataKey" }] : []));
    paramName = input('query', ...(ngDevMode ? [{ debugName: "paramName" }] : []));
    context = input(undefined, ...(ngDevMode ? [{ debugName: "context" }] : []));
    styleClass;
    requiredValidator = Validators.required;
    value = signal(null, ...(ngDevMode ? [{ debugName: "value" }] : []));
    disabled = signal(false, ...(ngDevMode ? [{ debugName: "disabled" }] : []));
    loading = signal(false, ...(ngDevMode ? [{ debugName: "loading" }] : []));
    size = input(...(ngDevMode ? [undefined, { debugName: "size" }] : []));
    filteredUsers = signal([], ...(ngDevMode ? [{ debugName: "filteredUsers" }] : []));
    searchTerms = new Subject();
    autocomplete = viewChild('autocomplete', ...(ngDevMode ? [{ debugName: "autocomplete" }] : []));
    onTouched = () => { };
    onModelChange = () => { };
    ngControl = null;
    http = inject(HttpClient);
    isInvalid = isInvalid;
    constructor() {
        this.ngControl = inject(NgControl, { self: true, optional: true });
        if (this.ngControl) {
            this.ngControl.valueAccessor = this;
        }
        effect(() => {
            if (this.ngControl?.control && this.required()) {
                this.ngControl.control.addValidators(Validators.required);
                this.ngControl.control.updateValueAndValidity();
            }
        });
        this.getUsers();
    }
    ngOnInit() {
        this.styleClass = this.class();
    }
    search(event) {
        this.loading.set(true);
        this.searchTerms.next(event.query);
    }
    onFocus() {
        if (this.filteredUsers().length > 0 && this.autocomplete()) {
            this.autocomplete()?.show();
        }
    }
    onSelect(event) {
        const selectedUser = event.value;
        this.value.set(selectedUser);
        this.onModelChange(selectedUser);
        this.onTouched();
        this.loading.set(false);
        this.filteredUsers.set([]);
        if (this.autocomplete()) {
            this.autocomplete()?.hide();
        }
    }
    onClear() {
        this.value.set(null);
        this.onModelChange(null);
        this.filteredUsers.set([]);
        this.loading.set(false);
    }
    writeValue(value) {
        this.value.set(value);
    }
    registerOnChange(fn) {
        this.onModelChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    setDisabledState(disabled) {
        this.disabled.set(disabled);
    }
    getUsers() {
        this.searchTerms
            .pipe(takeUntilDestroyed(), distinctUntilChanged(), tap(() => this.loading.set(true)), switchMap((term) => {
            if (!term) {
                this.filteredUsers.set([]);
                this.loading.set(false);
                return of([]);
            }
            const params = new HttpParams().set(this.paramName(), term);
            return this.http
                .get(this.apiUrl(), {
                params,
                context: this.context(),
            })
                .pipe(finalize(() => this.loading.set(false)), catchError((err) => {
                console.error('API search failed:', err);
                this.filteredUsers.set([]);
                return of({ [this.dataKey()]: [] });
            }));
        }))
            .subscribe({
            next: (users) => {
                this.filteredUsers.set((users[this.dataKey()] ?? []));
            },
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.3", ngImport: i0, type: UserSearchField, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.0.3", type: UserSearchField, isStandalone: true, selector: "mt-user-search-field", inputs: { hint: { classPropertyName: "hint", publicName: "hint", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, class: { classPropertyName: "class", publicName: "class", isSignal: true, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, apiUrl: { classPropertyName: "apiUrl", publicName: "apiUrl", isSignal: true, isRequired: true, transformFunction: null }, dataKey: { classPropertyName: "dataKey", publicName: "dataKey", isSignal: true, isRequired: false, transformFunction: null }, paramName: { classPropertyName: "paramName", publicName: "paramName", isSignal: true, isRequired: false, transformFunction: null }, context: { classPropertyName: "context", publicName: "context", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class": "this.styleClass" }, classAttribute: "grid gap-1" }, viewQueries: [{ propertyName: "autocomplete", first: true, predicate: ["autocomplete"], descendants: true, isSignal: true }], ngImport: i0, template: "@if (label()) {\n  <label\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\n    [for]=\"ngControl?.name || label()\"\n  >\n    {{ label() }}\n  </label>\n}\n<div class=\"relative\">\n  <p-inputgroup>\n    <p-autoComplete\n      #autocomplete=\"\"\n      [suggestions]=\"filteredUsers()\"\n      (completeMethod)=\"search($event)\"\n      (onSelect)=\"onSelect($event)\"\n      (onClear)=\"onClear()\"\n      (onFocus)=\"onFocus()\"\n      (onBlur)=\"onTouched()\"\n      [ngModel]=\"value()?.displayName\"\n      [disabled]=\"disabled() || readonly()\"\n      [id]=\"ngControl?.name || label()\"\n      [invalid]=\"isInvalid(ngControl?.control)\"\n      [placeholder]=\"placeholder()\"\n      class=\"w-full\"\n      appendTo=\"body\"\n      styleClass=\"w-full\"\n      [dropdown]=\"false\"\n      [size]=\"size()\"\n    >\n      <ng-template let-user pTemplate=\"item\">\n        <div class=\"flex items-center gap-2\">\n          <mt-avatar size=\"small\" icon=\"user.user-01\" />\n          <div class=\"flex align-items-center gap-3\">\n            <span class=\"font-medium\">{{ user.displayName }}</span>\n            <medium class=\"text-gray-500\">{{ \"@\" + user.userName }}</medium>\n          </div>\n        </div>\n      </ng-template>\n\n      <!-- <ng-template let-user #pTemplate=\"selecteditem\">\n        <div class=\"flex items-center gap-2\">\n          <mt-avatar size=\"small\" icon=\"user.user-01\" />\n          <div class=\"flex align-items-center gap-3\">\n            <span class=\"font-medium\">{{ user.displayName }}</span>\n            <medium class=\"text-gray-500\">{{ \"@\" + user.userName }}</medium>\n          </div>\n        </div>\n      </ng-template> -->\n    </p-autoComplete>\n    @if (hint()) {\n      <p-inputgroup-addon [mtTooltip]=\"hint()\" tooltipPosition=\"top\">\n        <mt-icon icon=\"general.help-circle\" />\n      </p-inputgroup-addon>\n    } @else {\n      <p-inputgroup-addon tooltipPosition=\"top\">\n        <mt-icon icon=\"user.user-03\" />\n      </p-inputgroup-addon>\n    }\n  </p-inputgroup>\n\n  @if (loading()) {\n    <mt-icon\n      icon=\"general.loading-01\"\n      class=\"animate-spin absolute right-3 bg-white top-1/2 -translate-y-1/2\"\n    />\n  }\n</div>\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\n", styles: [""], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: AutoCompleteModule }, { kind: "component", type: i2.AutoComplete, selector: "p-autoComplete, p-autocomplete, p-auto-complete", inputs: ["minLength", "minQueryLength", "delay", "panelStyle", "styleClass", "panelStyleClass", "inputStyle", "inputId", "inputStyleClass", "placeholder", "readonly", "scrollHeight", "lazy", "virtualScroll", "virtualScrollItemSize", "virtualScrollOptions", "autoHighlight", "forceSelection", "type", "autoZIndex", "baseZIndex", "ariaLabel", "dropdownAriaLabel", "ariaLabelledBy", "dropdownIcon", "unique", "group", "completeOnFocus", "showClear", "dropdown", "showEmptyMessage", "dropdownMode", "multiple", "addOnTab", "tabindex", "dataKey", "emptyMessage", "showTransitionOptions", "hideTransitionOptions", "autofocus", "autocomplete", "optionGroupChildren", "optionGroupLabel", "overlayOptions", "suggestions", "optionLabel", "optionValue", "id", "searchMessage", "emptySelectionMessage", "selectionMessage", "autoOptionFocus", "selectOnFocus", "searchLocale", "optionDisabled", "focusOnHover", "typeahead", "addOnBlur", "separator", "appendTo", "motionOptions"], outputs: ["completeMethod", "onSelect", "onUnselect", "onAdd", "onFocus", "onBlur", "onDropdownClick", "onClear", "onInputKeydown", "onKeyUp", "onShow", "onHide", "onLazyLoad"] }, { kind: "directive", type: i3.PrimeTemplate, selector: "[pTemplate]", inputs: ["type", "pTemplate"] }, { kind: "directive", type: Tooltip, selector: "[mtTooltip]" }, { kind: "ngmodule", type: InputGroupModule }, { kind: "component", type: i4.InputGroup, selector: "p-inputgroup, p-inputGroup, p-input-group", inputs: ["styleClass"] }, { kind: "ngmodule", type: InputGroupAddonModule }, { kind: "component", type: i5.InputGroupAddon, selector: "p-inputgroup-addon, p-inputGroupAddon", inputs: ["style", "styleClass"] }, { kind: "component", type: FieldValidation, selector: "mt-field-validation", inputs: ["control", "touched"] }, { kind: "component", type: Icon, selector: "mt-icon", inputs: ["icon"] }, { kind: "component", type: Avatar, selector: "mt-avatar", inputs: ["label", "icon", "image", "styleClass", "size", "shape", "badge", "badgeSize", "badgeSeverity"], outputs: ["onImageError"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.3", ngImport: i0, type: UserSearchField, decorators: [{
            type: Component,
            args: [{ selector: 'mt-user-search-field', standalone: true, imports: [
                        FormsModule,
                        AutoCompleteModule,
                        Tooltip,
                        InputGroupModule,
                        InputGroupAddonModule,
                        FieldValidation,
                        Icon,
                        Avatar,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        class: 'grid gap-1',
                    }, template: "@if (label()) {\n  <label\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\n    [for]=\"ngControl?.name || label()\"\n  >\n    {{ label() }}\n  </label>\n}\n<div class=\"relative\">\n  <p-inputgroup>\n    <p-autoComplete\n      #autocomplete=\"\"\n      [suggestions]=\"filteredUsers()\"\n      (completeMethod)=\"search($event)\"\n      (onSelect)=\"onSelect($event)\"\n      (onClear)=\"onClear()\"\n      (onFocus)=\"onFocus()\"\n      (onBlur)=\"onTouched()\"\n      [ngModel]=\"value()?.displayName\"\n      [disabled]=\"disabled() || readonly()\"\n      [id]=\"ngControl?.name || label()\"\n      [invalid]=\"isInvalid(ngControl?.control)\"\n      [placeholder]=\"placeholder()\"\n      class=\"w-full\"\n      appendTo=\"body\"\n      styleClass=\"w-full\"\n      [dropdown]=\"false\"\n      [size]=\"size()\"\n    >\n      <ng-template let-user pTemplate=\"item\">\n        <div class=\"flex items-center gap-2\">\n          <mt-avatar size=\"small\" icon=\"user.user-01\" />\n          <div class=\"flex align-items-center gap-3\">\n            <span class=\"font-medium\">{{ user.displayName }}</span>\n            <medium class=\"text-gray-500\">{{ \"@\" + user.userName }}</medium>\n          </div>\n        </div>\n      </ng-template>\n\n      <!-- <ng-template let-user #pTemplate=\"selecteditem\">\n        <div class=\"flex items-center gap-2\">\n          <mt-avatar size=\"small\" icon=\"user.user-01\" />\n          <div class=\"flex align-items-center gap-3\">\n            <span class=\"font-medium\">{{ user.displayName }}</span>\n            <medium class=\"text-gray-500\">{{ \"@\" + user.userName }}</medium>\n          </div>\n        </div>\n      </ng-template> -->\n    </p-autoComplete>\n    @if (hint()) {\n      <p-inputgroup-addon [mtTooltip]=\"hint()\" tooltipPosition=\"top\">\n        <mt-icon icon=\"general.help-circle\" />\n      </p-inputgroup-addon>\n    } @else {\n      <p-inputgroup-addon tooltipPosition=\"top\">\n        <mt-icon icon=\"user.user-03\" />\n      </p-inputgroup-addon>\n    }\n  </p-inputgroup>\n\n  @if (loading()) {\n    <mt-icon\n      icon=\"general.loading-01\"\n      class=\"animate-spin absolute right-3 bg-white top-1/2 -translate-y-1/2\"\n    />\n  }\n</div>\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\n" }]
        }], ctorParameters: () => [], propDecorators: { hint: [{ type: i0.Input, args: [{ isSignal: true, alias: "hint", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], class: [{ type: i0.Input, args: [{ isSignal: true, alias: "class", required: false }] }], readonly: [{ type: i0.Input, args: [{ isSignal: true, alias: "readonly", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], apiUrl: [{ type: i0.Input, args: [{ isSignal: true, alias: "apiUrl", required: true }] }], dataKey: [{ type: i0.Input, args: [{ isSignal: true, alias: "dataKey", required: false }] }], paramName: [{ type: i0.Input, args: [{ isSignal: true, alias: "paramName", required: false }] }], context: [{ type: i0.Input, args: [{ isSignal: true, alias: "context", required: false }] }], styleClass: [{
                type: HostBinding,
                args: ['class']
            }], size: [{ type: i0.Input, args: [{ isSignal: true, alias: "size", required: false }] }], autocomplete: [{ type: i0.ViewChild, args: ['autocomplete', { isSignal: true }] }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { UserSearchField };
//# sourceMappingURL=masterteam-components-user-search-field.mjs.map
