import { AbstractForm } from '@/shared/abstractClasses';
import {
  EconomicCodeComponent,
  FiscalIdComponent,
  GuildIdComponent,
  LicenseStartsAtComponent,
  NameComponent,
  PartnerTokenComponent,
} from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { fieldControl } from '@/shared/constants/fields';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { IBusinessActivityRequest, IBusinessActivityResponse } from '../../models';
import { PartnerConsumerBusinessActivitiesService } from '../../services/businessActivities.service';

@Component({
  selector: 'partner-consumer-businessActivities-form-content',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    NameComponent,
    EconomicCodeComponent,
    FiscalIdComponent,
    PartnerTokenComponent,
    GuildIdComponent,
    LicenseStartsAtComponent,
    FormFooterActionsComponent,
    Divider,
  ],
})
export class ConsumerBusinessActivitiesFormComponent extends AbstractForm<
  IBusinessActivityRequest,
  IBusinessActivityResponse
> {
  private readonly service = inject(PartnerConsumerBusinessActivitiesService);

  @Input({ required: true }) consumerId!: string;
  @Input() businessActivityId!: string;

  initForm = () => {
    const form = this.fb.group({
      name: fieldControl.name(this.initialValues?.name || ''),
      economic_code: fieldControl.economic_code(this.initialValues?.economic_code || ''),
      fiscal_id: fieldControl.fiscal_id(this.initialValues?.fiscal_id || ''),
      partner_token: fieldControl.partner_token(this.initialValues?.partner_token || ''),
      guild_id: fieldControl.guild_id(this.initialValues?.guild?.id || ''),
      license_starts_at: [''],
    });

    if (this.editMode) {
      // @ts-ignore
      form.removeControl('license_starts_at');
    } else {
      form.addControl(
        'license_starts_at',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: fieldControl.license_starts_at('')[1],
        }),
      );
    }

    return form;
  };

  form = this.initForm();

  override ngOnChanges(): void {
    this.form = this.initForm();
  }

  submitForm() {
    const formValue = this.form.value as IBusinessActivityRequest;
    formValue.economic_code = String(formValue.economic_code);
    if (this.editMode) {
      return this.service.update(this.consumerId, this.businessActivityId, formValue);
    }
    return this.service.create(this.consumerId, formValue);
  }
}
