import { MustMatch, usernameValidator } from '@/core/validators';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { InputComponent, SharedPasswordInputComponent } from '@/shared/components';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { fieldControl } from '@/shared/constants';
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';

@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: fieldControl.name(this.initialValues?.name || ''),
      code: fieldControl.code(this.initialValues?.code || ''),
      username: fieldControl.username(),
      password: fieldControl.password(),
      confirmPassword: fieldControl.confirmPassword(),
    });

    if (!this.editMode) {
      form.controls.username.setValidators([Validators.required, usernameValidator()]);
      form.controls.username.updateValueAndValidity({ emitEvent: false });
      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);
  }
}
