import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { EventEmitter, Output, ContentChild, Input, ChangeDetectionStrategy, Component } from '@angular/core';
import * as i2 from '@angular/forms';
import { NgForm, Validators, ReactiveFormsModule } from '@angular/forms';
import * as i3 from '@angular/material/form-field';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import * as i4 from '@angular/material/radio';
import { MatRadioModule } from '@angular/material/radio';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Subscription } from 'rxjs';
import * as uuid from 'uuid';
import { SdSuffixDefDirective, SdLabelDefDirective, SdViewDefDirective } from '@sd-angular/core/forms/directives';
import { SdFormControl } from '@sd-angular/core/forms/models';
import { SdEmptyPipe } from '@sd-angular/core/pipes';
import { SdLabel } from '@sd-angular/core/forms/label';
import { SdHrefDirective } from '@sd-angular/core/directives';

/* eslint-disable @angular-eslint/no-input-rename */
/* eslint-disable @typescript-eslint/no-explicit-any */
// eslint-disable-next-line @angular-eslint/component-class-suffix
class SdRadio {
    ref;
    id = `I${uuid.v4()}`;
    autoId;
    set _autoId(val) {
        if (!val) {
            return;
        }
        this.autoId = `forms-radio-${val}`;
    }
    #name = uuid.v4();
    set name(val) {
        if (val) {
            this.#name = val;
        }
    }
    formControl = new SdFormControl();
    // get isNumber() {
    //   if (this.#model || this.#model === 0) {
    //     return typeof (this.#model) === 'number';
    //   }
    //   if (this.items?.length) {
    //     if (this.valueField) {
    //       return typeof (this.items[0][this.valueField]) === 'number';
    //     } else {
    //       return typeof (this.items[0]) === 'number';
    //     }
    //   }
    //   return false;
    // }
    #form;
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                this.#form = val.form;
            }
            else {
                this.#form = val;
            }
        }
    }
    label;
    placeholder;
    display = 'row';
    set _display(display) {
        this.display = display || 'row';
    }
    // Model
    set model(value) {
        if (value !== this.formControl.value) {
            this.formControl.setValue(value, {
                emitEvent: false,
            });
        }
    }
    // Items
    items = [];
    set pItems(items) {
        if (!Array.isArray(items)) {
            this.items = [];
        }
        else {
            this.items = items;
        }
    }
    valueField;
    displayField;
    // Validator
    required = false;
    set _required(val) {
        this.required = val === '' || !!val;
        this.#updateValidator();
    }
    inlineError;
    set _inlineError(val) {
        this.inlineError = val;
        this.#updateValidator();
    }
    // Optional
    set disabled(val) {
        val = val === '' || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    viewed = false;
    set _viewed(val) {
        this.viewed = val === '' || !!val;
    }
    hyperlink;
    sdSuffixDef;
    sdLabelDef;
    sdViewDef;
    modelChange = new EventEmitter();
    sdChange = new EventEmitter();
    sdSelection = new EventEmitter();
    #subscription = new Subscription();
    constructor(ref) {
        this.ref = ref;
    }
    get viewedText() {
        return this.items?.find(e => this.formControl?.value?.toString() === e?.[this.valueField]?.toString()) ?? '';
    }
    ngOnInit() {
        this.#subscription.add(this.formControl.sdChanges.subscribe(() => {
            // this.formControl.updateValueAndValidity();
            this.ref.markForCheck();
        }));
    }
    ngAfterViewInit() {
        this.#subscription.add(this.formControl.valueChanges.subscribe(value => {
            const val = value;
            // if (this.isNumber && Number.isNumber(value)) {
            //   val = +value;
            // }
            this.modelChange.emit(val);
            this.sdChange.emit(val);
            this.sdSelection.emit({
                value: val,
                item: this.items?.find(e => val?.toString() === e?.[this.valueField]?.toString()),
            });
        }));
        this.#form?.addControl(this.#name, this.formControl);
    }
    ngOnDestroy() {
        this.#subscription.unsubscribe();
        this.#form?.removeControl(this.#name);
    }
    #updateValidator = () => {
        this.formControl.clearValidators();
        const validators = [];
        if (this.required) {
            validators.push(Validators.required);
        }
        if (this.inlineError) {
            validators.push(this.customInlineErrorValidator());
        }
        this.formControl.setValidators(validators);
        this.formControl.updateValueAndValidity();
    };
    // Hàm tạo Validators tùy chỉnh cho inlineError
    customInlineErrorValidator() {
        return () => {
            return { inlineError: true };
        };
    }
    reValidate = () => {
        this.formControl.updateValueAndValidity({ emitEvent: true });
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdRadio, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: SdRadio, isStandalone: true, selector: "sd-radio", inputs: { _autoId: ["autoId", "_autoId"], name: "name", form: "form", label: "label", placeholder: "placeholder", _display: ["display", "_display"], model: "model", pItems: ["items", "pItems"], valueField: "valueField", displayField: "displayField", _required: ["required", "_required"], _inlineError: ["inlineError", "_inlineError"], disabled: "disabled", _viewed: ["viewed", "_viewed"], hyperlink: "hyperlink" }, outputs: { modelChange: "modelChange", sdChange: "sdChange", sdSelection: "sdSelection" }, queries: [{ propertyName: "sdSuffixDef", first: true, predicate: SdSuffixDefDirective, descendants: true }, { propertyName: "sdLabelDef", first: true, predicate: SdLabelDefDirective, descendants: true }, { propertyName: "sdViewDef", first: true, predicate: SdViewDefDirective, descendants: true }], ngImport: i0, template: "@if (viewed) {\r\n  @if (sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n  } @else if (label) {\r\n    <div class=\"T14R text-black400\">{{ label }}</div>\r\n  }\r\n  @if (hyperlink) {\r\n    <!-- N\u1EBFu c\u00F3 hyperlink th\u00EC d\u00F9ng th\u1EBB a -->\r\n    <a [sdHref]=\"hyperlink\">{{ viewedText }}</a>\r\n  } @else {\r\n    <!-- Ngo\u00E0i ra d\u00F9ng th\u1EBB m\u1EB7c \u0111\u1ECBnh -->\r\n    <div class=\"T14M\">{{ viewedText | sdEmpty }}</div>\r\n  }\r\n} @else {\r\n  <section [ngClass]=\"{ 'c-section': display === 'row' }\">\r\n    @if (sdLabelDef?.templateRef) {\r\n      <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n    } @else if (label) {\r\n      <sd-label [label]=\"label\" [required]=\"required\"></sd-label>\r\n    }\r\n    <mat-radio-group\r\n      [class.c-radio-group-column]=\"display === 'column'\"\r\n      [class.c-radio-group-row]=\"display === 'row'\"\r\n      [formControl]=\"formControl\"\r\n      [attr.data-autoId]=\"autoId\">\r\n      @for (item of items; track item[valueField]) {\r\n        <mat-radio-button color=\"primary\" [class.m-0]=\"display === 'column'\" [class.mr-16]=\"display === 'row'\" [value]=\"item[valueField]\">\r\n          {{ item[displayField] }}\r\n        </mat-radio-button>\r\n      }\r\n    </mat-radio-group>\r\n\r\n    @if (formControl.errors?.['required'] && formControl.touched) {\r\n      <mat-error>\r\n        {{ 'Vui l\u00F2ng nh\u1EADp th\u00F4ng tin' }}\r\n      </mat-error>\r\n    } @else if (formControl.errors?.['inlineError'] && formControl.touched) {\r\n      <mat-error>\r\n        {{ inlineError }}\r\n      </mat-error>\r\n    }\r\n  </section>\r\n}\r\n", styles: [":host{height:100%;display:flex;flex-direction:column}:host ::ng-deep label.mdc-label{margin-bottom:0}.c-section{align-content:center;align-items:center}.c-radio-group-column{flex:1;display:flex;flex-direction:column;align-items:flex-start}.c-radio-group-row{flex:1;display:flex;flex-direction:row;align-items:center}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "directive", type: i3.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "ngmodule", type: MatRadioModule }, { kind: "directive", type: i4.MatRadioGroup, selector: "mat-radio-group", inputs: ["color", "name", "labelPosition", "value", "selected", "disabled", "required", "disabledInteractive"], outputs: ["change"], exportAs: ["matRadioGroup"] }, { kind: "component", type: i4.MatRadioButton, selector: "mat-radio-button", inputs: ["id", "name", "aria-label", "aria-labelledby", "aria-describedby", "disableRipple", "tabIndex", "checked", "value", "labelPosition", "disabled", "required", "color", "disabledInteractive"], outputs: ["change"], exportAs: ["matRadioButton"] }, { kind: "component", type: SdLabel, selector: "sd-label", inputs: ["label", "description", "required", "helperText"] }, { kind: "pipe", type: SdEmptyPipe, name: "sdEmpty" }, { kind: "directive", type: SdHrefDirective, selector: "a[sdHref]", inputs: ["sdHref"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdRadio, decorators: [{
            type: Component,
            args: [{ selector: 'sd-radio', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [CommonModule, ReactiveFormsModule, MatTooltipModule, MatFormFieldModule, MatIconModule, MatRadioModule, SdLabel, SdEmptyPipe, SdHrefDirective], template: "@if (viewed) {\r\n  @if (sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n  } @else if (label) {\r\n    <div class=\"T14R text-black400\">{{ label }}</div>\r\n  }\r\n  @if (hyperlink) {\r\n    <!-- N\u1EBFu c\u00F3 hyperlink th\u00EC d\u00F9ng th\u1EBB a -->\r\n    <a [sdHref]=\"hyperlink\">{{ viewedText }}</a>\r\n  } @else {\r\n    <!-- Ngo\u00E0i ra d\u00F9ng th\u1EBB m\u1EB7c \u0111\u1ECBnh -->\r\n    <div class=\"T14M\">{{ viewedText | sdEmpty }}</div>\r\n  }\r\n} @else {\r\n  <section [ngClass]=\"{ 'c-section': display === 'row' }\">\r\n    @if (sdLabelDef?.templateRef) {\r\n      <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n    } @else if (label) {\r\n      <sd-label [label]=\"label\" [required]=\"required\"></sd-label>\r\n    }\r\n    <mat-radio-group\r\n      [class.c-radio-group-column]=\"display === 'column'\"\r\n      [class.c-radio-group-row]=\"display === 'row'\"\r\n      [formControl]=\"formControl\"\r\n      [attr.data-autoId]=\"autoId\">\r\n      @for (item of items; track item[valueField]) {\r\n        <mat-radio-button color=\"primary\" [class.m-0]=\"display === 'column'\" [class.mr-16]=\"display === 'row'\" [value]=\"item[valueField]\">\r\n          {{ item[displayField] }}\r\n        </mat-radio-button>\r\n      }\r\n    </mat-radio-group>\r\n\r\n    @if (formControl.errors?.['required'] && formControl.touched) {\r\n      <mat-error>\r\n        {{ 'Vui l\u00F2ng nh\u1EADp th\u00F4ng tin' }}\r\n      </mat-error>\r\n    } @else if (formControl.errors?.['inlineError'] && formControl.touched) {\r\n      <mat-error>\r\n        {{ inlineError }}\r\n      </mat-error>\r\n    }\r\n  </section>\r\n}\r\n", styles: [":host{height:100%;display:flex;flex-direction:column}:host ::ng-deep label.mdc-label{margin-bottom:0}.c-section{align-content:center;align-items:center}.c-radio-group-column{flex:1;display:flex;flex-direction:column;align-items:flex-start}.c-radio-group-row{flex:1;display:flex;flex-direction:row;align-items:center}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }], propDecorators: { _autoId: [{
                type: Input,
                args: ['autoId']
            }], name: [{
                type: Input
            }], form: [{
                type: Input
            }], label: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], _display: [{
                type: Input,
                args: ['display']
            }], model: [{
                type: Input
            }], pItems: [{
                type: Input,
                args: ['items']
            }], valueField: [{
                type: Input,
                args: [{ required: true }]
            }], displayField: [{
                type: Input,
                args: [{ required: true }]
            }], _required: [{
                type: Input,
                args: ['required']
            }], _inlineError: [{
                type: Input,
                args: ['inlineError']
            }], disabled: [{
                type: Input
            }], _viewed: [{
                type: Input,
                args: ['viewed']
            }], hyperlink: [{
                type: Input
            }], sdSuffixDef: [{
                type: ContentChild,
                args: [SdSuffixDefDirective]
            }], sdLabelDef: [{
                type: ContentChild,
                args: [SdLabelDefDirective]
            }], sdViewDef: [{
                type: ContentChild,
                args: [SdViewDefDirective]
            }], modelChange: [{
                type: Output
            }], sdChange: [{
                type: Output
            }], sdSelection: [{
                type: Output
            }] } });

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

export { SdRadio };
//# sourceMappingURL=sd-angular-core-forms-radio.mjs.map
