import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ZardFormModule } from '@shared/components/form/form.module';
import { ZardInputDirective } from '@shared/components/input/input.directive';
import { Permission } from 'src/app/core/interfaces/role';

@Component({
  selector: 'app-permission-form',
  standalone: true,
  templateUrl: './permission-form.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule, ReactiveFormsModule, ZardFormModule, ZardInputDirective],
})
export class PermissionForm {
  @Output() save = new EventEmitter<Permission>();
  @Output() cancel = new EventEmitter<void>();

  private _value?: Permission;
  @Input() set value(v: Permission | undefined) {
    this._value = v;
    this.hydrateFromValue(v);
  }
  get value(): Permission | undefined {
    return this._value;
  }

  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['', Validators.required],
      description: [''],
    });
  }

  private hydrateFromValue(v?: Permission) {
    this.form.reset({
      name: v?.name ?? '',
      description: v?.description ?? '',
    });
  }

  isInvalid(control: string): boolean {
    const ctrl = this.form.get(control);
    return !!(ctrl && ctrl.invalid && (ctrl.touched || this.submitted));
  }

  errorMessage(control: string): string | null {
    const c = this.form.get(control);
    if (!c || !c.errors) return null;
    if (c.errors['required']) return 'Ce champ est obligatoire';
    return null;
  }

  onSubmit() {
    this.submitted = true;
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    const raw = this.form.getRawValue() as any;
    const payload: Permission = {
      id: this.value?.id ?? '',
      name: raw.name,
      description: raw.description,
    };
    this.save.emit(payload);
  }
}


