/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant.aurora.yaml
 */
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  output,
} from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { SearchSelect, ValidationMessagePipe, type Option } from '@aurora';
import { provideTranslocoScope, TranslocoDirective } from '@jsverse/transloco';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
import { HlmLabelImports } from '@spartan-ng/helm/label';
import { HlmSwitchImports } from '@spartan-ng/helm/switch';
import { type IamTenant } from '@src/src/app/aurora.types';

@Component({
  selector: 'au-tenant-form',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ReactiveFormsModule,
    TranslocoDirective,
    ValidationMessagePipe,
    HlmFieldImports,
    HlmInputImports,
    HlmLabelImports,
    HlmSwitchImports,
    SearchSelect,
  ],
  providers: [provideTranslocoScope('iam')],
  template: `
    <ng-container *transloco="let t; scope: 'iam'">
      <!-- #region AURORA:FORM-FIELDS-START -->
      <form
        class="grid grid-cols-1 gap-x-4 gap-y-5 md:grid-cols-12"
        [formGroup]="signalForm"
        (ngSubmit)="submit()"
      >
        <hlm-field class="col-span-12 md:col-span-12">
          <label
            hlmLabel
            for="parentId"
          >
            {{ t('iam.tenant.ParentId') }}
          </label>
          <au-search-select
            [inputId]="'parentId'"
            [value]="signalForm.controls['parentId'].value"
            [options]="parentAsOptions()"
            [placeholder]="t('Select')"
            [emptyMessage]="t('NoResults')"
            (valueChange)="
              signalForm.controls['parentId'].setValue($event); signalForm.markAsDirty()
            "
            (touched)="signalForm.controls['parentId'].markAsTouched()"
          />
          <hlm-field-error>
            {{ signalForm.get('parentId')?.errors | validationMessage }}
          </hlm-field-error>
        </hlm-field>

        <hlm-field class="col-span-12 md:col-span-12">
          <label
            hlmLabel
            for="name"
          >
            {{ t('iam.tenant.Name') }}
            <span
              aria-hidden="true"
              class="text-muted-foreground/70 align-top text-xs"
            >
              *
            </span>
          </label>
          <input
            id="name"
            aria-required="true"
            hlmInput
            formControlName="name"
            maxlength="128"
          />
          <hlm-field-error>
            {{ signalForm.get('name')?.errors | validationMessage }}
          </hlm-field-error>
        </hlm-field>
        <hlm-field class="col-span-12 md:col-span-12">
          <label
            hlmLabel
            for="code"
          >
            {{ t('iam.tenant.Code') }}
          </label>
          <input
            id="code"
            hlmInput
            formControlName="code"
            maxlength="64"
          />
          <hlm-field-error>
            {{ signalForm.get('code')?.errors | validationMessage }}
          </hlm-field-error>
        </hlm-field>

        <hlm-field class="col-span-12 pt-5 md:col-span-12">
          <label
            class="flex items-center"
            hlmLabel
            for="isActive"
          >
            <hlm-switch
              class="mr-2"
              inputId="isActive"
              formControlName="isActive"
            />
            {{ t('iam.tenant.IsActive') }}
          </label>
        </hlm-field>
      </form>
      <!-- #endregion AURORA:FORM-FIELDS-END -->
    </ng-container>
  `,
})
export class TenantFormComponent {
  // injections
  private readonly fb = inject(FormBuilder);

  // inputs
  readonly initial = input<IamTenant | null>(null);
  readonly mode = input.required<'new' | 'edit'>();

  // outputs
  readonly save = output<IamTenant>();
  readonly cancel = output<void>();
  readonly parentOptions = input<IamTenant[]>([]);

  protected readonly parentAsOptions = computed<Option[]>(() =>
    this.parentOptions().map((o) => ({ value: o.id, label: o.name })),
  );

  readonly signalForm: FormGroup = this.fb.group({
    id: [null],
    parentId: [null, [Validators.minLength(36), Validators.maxLength(36)]],
    name: ['', [Validators.required, Validators.maxLength(128)]],
    code: ['', [Validators.maxLength(64)]],
    logo: [null],
    isActive: [false],
  });

  constructor() {
    effect(() => {
      const init = this.initial();
      if (init) this.signalForm.reset(init);
    });
  }

  submit(): void {
    if (this.signalForm.invalid) {
      this.signalForm.markAllAsTouched();
      return;
    }
    this.save.emit(this.signalForm.value as IamTenant);
  }
}
