import { AbstractFormDialog } from '@/shared/abstractClasses';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { UikitFlatpickrJalaliComponent } from '@/uikit';
import { Component, computed, inject, Input } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { ILicenseRequest, ILicenseResponse } from '../../models';
import { LicensesService } from '../../services/licenses.service';

@Component({
  selector: 'partner-consumer-license-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    SharedDialogComponent,
    FormFooterActionsComponent,
    UikitFlatpickrJalaliComponent,
  ],
})
export class ConsumerLicenseFormComponent extends AbstractFormDialog<
  ILicenseRequest,
  ILicenseResponse
> {
  @Input({ required: true }) consumerId!: string;
  @Input() licenseId?: string;
  private service = inject(LicensesService);

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

  initForm = () => {
    const form = this.fb.group({
      starts_at: [this.initialValues?.starts_at || ''],
      partner_id: [this.initialValues?.partner?.id || ''],
    });

    return form;
  };

  form = this.initForm();

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

    this.form = this.initForm();
  }

  override submitForm(payload: ILicenseRequest) {
    if (this.editMode) {
      return this.service.update(this.consumerId!, this.licenseId!, payload);
    }
    return this.service.create(this.consumerId, payload);
  }
}
