import { MustMatch } from '@/core/validators';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { InputComponent, SharedPasswordInputComponent } from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, computed, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { IProviderRequest, IProviderResponse } from '../models';
import { ProvidersService } from '../services/main.service';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';

@Component({
  selector: 'provider-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    SharedDialogComponent,
    InputComponent,
    FormFooterActionsComponent,
    Divider,
    SharedPasswordInputComponent,
  ],
})
export class ProviderFormComponent extends AbstractFormDialog<IProviderRequest, IProviderResponse> {
  @Input() providerId?: string;
  private service = inject(ProvidersService);

  private initForm() {
    const form = this.fb.group({
      name: [this.initialValues?.name, [Validators.required]],
      code: [this.initialValues?.code, [Validators.required]],
      username: [''],
      password: [''],
      confirmPassword: [''],
    });

    if (!this.editMode) {
      form.addControl(
        'username',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: [Validators.required],
        }),
      );
      form.addControl(
        'password',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: [Validators.required],
        }),
      );
      form.addControl(
        'confirmPassword',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: [Validators.required],
        }),
      );
      form.addValidators([MustMatch('password', 'confirmPassword')]);
    } else {
      // @ts-ignore
      form.removeControl('username');
      // @ts-ignore
      form.removeControl('password');
      // @ts-ignore
      form.removeControl('confirmPassword');
      form.removeValidators([MustMatch('password', 'confirmPassword')]);
    }

    return form;
  }

  form = this.initForm();

  preparedTitle = computed(() => `${this.editMode ? 'ویرایش' : 'ایجاد'} ارایه‌دهنده`);

  override ngOnChanges() {
    this.form.patchValue(this.initialValues ?? {});
    if (this.editMode && !this.providerId) {
      throw 'missing some arguments';
    }
    this.initForm();
  }

  override submitForm(payload: IProviderRequest) {
    if (this.editMode) {
      return this.service.update(this.providerId!, payload);
    }
    // @ts-ignore
    const { confirmPassword, ...rest } = payload;
    return this.service.create(rest);
  }
}
