/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tag.aurora.yaml
 */
import { ChangeDetectionStrategy, Component, effect, inject, input, output } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ValidationMessagePipe } 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 { type IamTag } from '@src/src/app/aurora.types';

@Component({
  selector: 'au-tag-form',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ReactiveFormsModule,
    TranslocoDirective,
    ValidationMessagePipe,
    HlmFieldImports,
    HlmInputImports,
    HlmLabelImports,
  ],
  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="name"
          >
            {{ t('iam.tag.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="64"
          />
          <hlm-field-error>
            {{ signalForm.get('name')?.errors | validationMessage }}
          </hlm-field-error>
        </hlm-field>
      </form>
      <!-- #endregion AURORA:FORM-FIELDS-END -->
    </ng-container>
  `,
})
export class TagFormComponent {
  // injections
  private readonly fb = inject(FormBuilder);

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

  // outputs
  readonly save = output<IamTag>();
  readonly cancel = output<void>();
  readonly signalForm: FormGroup = this.fb.group({
    id: [null],
    name: ['', [Validators.required, Validators.maxLength(64)]],
  });
  constructor() {
    effect(() => {
      const init = this.initial();
      if (!init) return;
      this.signalForm.reset(init);
    });
  }

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