import { Maybe } from '@/core';
import { MustMatch, usernameValidator } from '@/core/validators';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import {
  CodeComponent,
  NameComponent,
  SharedPasswordInputComponent,
  UsernameComponent,
} from '@/shared/components';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { onSelectFileArgs } from '@/shared/components/uploadFile/model';
import { SharedUploadFileComponent } from '@/shared/components/uploadFile/upload-file.component';
import { fieldControl } from '@/shared/constants';
import { buildFormData } from '@/utils';
import { Component, computed, inject, Input, signal } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { IPartnerRequest, IPartnerResponse } from '../models';
import { PartnersService } from '../services/main.service';

@Component({
  selector: 'partner-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    SharedDialogComponent,
    FormFooterActionsComponent,
    Divider,
    SharedPasswordInputComponent,
    SharedUploadFileComponent,
    UsernameComponent,
    NameComponent,
    CodeComponent,
  ],
})
export class GuildFormComponent extends AbstractFormDialog<IPartnerRequest, IPartnerResponse> {
  @Input() partnerId?: string;
  private service = inject(PartnersService);

  private initForm() {
    const formConfig = {
      name: fieldControl.name(this.initialValues?.name || ''),
      code: fieldControl.code(this.initialValues?.code || ''),
      username: [''],
      password: [''],
      confirmPassword: [''],
    };

    if (!this.editMode) {
      formConfig.username = fieldControl.username();
      formConfig.password = fieldControl.password();
      formConfig.confirmPassword = fieldControl.confirmPassword();
    }

    const form = this.fb.group(formConfig);

    if (!this.editMode) {
      // @ts-ignore
      form.controls['username'].setValidators([Validators.required, usernameValidator()]);
      // @ts-ignore
      form.controls['username'].updateValueAndValidity({ emitEvent: false });
      form.addValidators([MustMatch('password', 'confirmPassword')]);
    }

    return form;
  }

  logo = signal<Maybe<File>>(null);

  form = this.initForm();

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

  changeFile(payload: onSelectFileArgs) {
    this.logo.set(payload.file);
  }

  override ngOnChanges() {
    this.form = this.initForm();
    this.form.patchValue((this.initialValues ?? {}) as Partial<Record<string, unknown>>);
    if (this.editMode && !this.partnerId) {
      throw 'missing some arguments';
    }
  }

  override submitForm(payload: IPartnerRequest) {
    const skipFields = this.editMode
      ? ['confirmPassword', 'username', 'password']
      : ['confirmPassword'];
    const formData = buildFormData(this.form, { logo: this.logo() }, skipFields);

    if (this.editMode) {
      return this.service.update(this.partnerId!, formData);
    }
    return this.service.create(formData);
  }
}
