import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { CommonNzModule } from './../../../../../common.nz.module';

export interface TeamFormModalData {
  type: 'add' | 'edit';
  params: {
    id?: number;
    name?: string;
    department?: number;
  };
  departments: BasicData.Department[];
}

@Component({
  selector: 'team-form',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './form.component.html',
  styleUrl: './form.component.less',
})
export class TeamFormComponent {
  readonly nzModalData: TeamFormModalData = inject(NZ_MODAL_DATA);
  validateForm = this.fb.group({
    name: this.fb.control<string>('', [Validators.required]),
    id: this.fb.control<number | undefined>(undefined),
    department: this.fb.control<number | undefined>(undefined, [Validators.required]),
  });
  loading = false;
  constructor(private fb: NonNullableFormBuilder) {}
  ngOnInit() {
    this.init();
  }
  async init() {
    if (this.nzModalData.type === 'edit') {
      const { name, id, department } = this.nzModalData.params;
      this.validateForm.patchValue({
        name,
        id,
        department,
      });
    } else {
      this.validateForm.patchValue({
        department: this.nzModalData.params.department,
      });
    }
  }
  resetName() {
    const nameControl = this.validateForm.get('name');
    if (nameControl) {
      nameControl.setValue('');
      nameControl.markAsUntouched();
      nameControl.markAsPending();
    }
  }
  async submit() {
    if (this.loading) return;
    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return Promise.reject();
    }
    this.loading = true;
    const values = this.validateForm.value;
    return Promise.resolve({
      name: values.name!,
      id: values.id,
      department: values.department!,
    });
  }
  get departments() {
    return this.nzModalData.departments;
  }
}
