import { AbstractFormDialog } from '@/shared/abstractClasses';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import {
  CodeComponent,
  NameComponent,
  SkuTypeComponent,
  VatComponent,
} from '@/shared/components/fields';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { fieldControl } from '@/shared/constants/fields';
import { Component, Input, inject } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { IStockKeepingUnitRequest, IStockKeepingUnitResponse } from '../../models';
import { StockKeepingUnitsService } from '../../services/stockKeepingUnits.service';

@Component({
  selector: 'stock-keeping-unit-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    SharedDialogComponent,
    NameComponent,
    CodeComponent,
    VatComponent,
    SkuTypeComponent,
    FormFooterActionsComponent,
  ],
})
export class StockKeepingUnitFormComponent extends AbstractFormDialog<
  IStockKeepingUnitRequest,
  IStockKeepingUnitResponse
> {
  @Input({ required: true }) guildId!: string;
  @Input() stockKeepingUnitId?: string;

  private readonly service = inject(StockKeepingUnitsService);

  form = this.fb.group({
    code: fieldControl.code(this.initialValues?.code || ''),
    name: fieldControl.name(this.initialValues?.name || ''),
    VAT: fieldControl.VAT(String(this.initialValues?.VAT ?? 0)),
    type: fieldControl.type(this.initialValues?.type || 'GOLD'),
    is_public: fieldControl.is_public(String(this.initialValues?.is_public ?? true), false),
    is_domestic: fieldControl.is_domestic(String(this.initialValues?.is_domestic ?? true), false),
  });

  override ngOnChanges() {
    this.form.patchValue({
      code: this.initialValues?.code ?? '',
      name: this.initialValues?.name ?? '',
      VAT: String(this.initialValues?.VAT ?? 0),
      type: this.initialValues?.type ?? 'GOLD',
      is_public: String(this.initialValues?.is_public ?? true),
      is_domestic: String(this.initialValues?.is_domestic ?? true),
    });
    if (this.editMode && !this.stockKeepingUnitId) {
      throw 'missing some arguments';
    }
  }

  override submitForm(payload: IStockKeepingUnitRequest) {
    const preparedPayload: IStockKeepingUnitRequest = {
      ...payload,
      VAT: Number(payload.VAT),
      is_public: String(payload.is_public) === 'true',
      is_domestic: String(payload.is_domestic) === 'true',
    };
    if (this.editMode) {
      return this.service.update(this.guildId, this.stockKeepingUnitId!, preparedPayload);
    }
    return this.service.create(this.guildId, preparedPayload);
  }
}
