import { Maybe } from '@/core';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { CodeComponent, NameComponent, SharedDialogComponent } from '@/shared/components';
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, inject, Input, signal } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { IProfileRequestPayload, IProfileResponse } from '../models';
import { ProfileService } from '../services/main.service';

@Component({
  selector: 'partner-profile-form',
  templateUrl: 'form.component.html',
  imports: [
    ReactiveFormsModule,
    FormFooterActionsComponent,
    SharedDialogComponent,
    NameComponent,
    CodeComponent,
    SharedUploadFileComponent,
  ],
})
export class PartnerProfileFormComponent extends AbstractFormDialog<
  IProfileRequestPayload,
  IProfileResponse
> {
  @Input() partnerId?: string;
  private service = inject(ProfileService);

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

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

    return form;
  }

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

  form = this.initForm();

  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: IProfileRequestPayload) {
    const formData = buildFormData(this.form, { logo: this.logo() });

    return this.service.updateProfile(formData);
  }
}
