import { IGoodResponse } from '@/domains/pos/models/good.io';
import { AbstractDialog } from '@/shared/abstractClasses/abstract-dialog';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { Component, computed, EventEmitter, inject, Input, Output, signal } from '@angular/core';
import { IGoldPayload, IPosOrderItem, IStandardPayload, TPosOrderGoodPayload } from '../models';
import { PosLandingStore } from '../store/main.store';
import { PosGoldPayloadFormComponent } from './payloads/gold/form.component';
import { PosStandardPayloadFormComponent } from './payloads/standard/form.component';

@Component({
  selector: 'pos-payload-form-dialog',
  templateUrl: './payload-form.component.html',
  imports: [PosGoldPayloadFormComponent, SharedDialogComponent, PosStandardPayloadFormComponent],
})
export class PayloadFormDialogComponent extends AbstractDialog {
  @Input({ required: true }) good!: IGoodResponse;
  @Input() initialValues?: IPosOrderItem;
  @Input() orderItemId?: string;
  @Output() onSubmit = new EventEmitter<TPosOrderGoodPayload>();

  private readonly store = inject(PosLandingStore);

  totalAmount = signal<number>(0);
  preparedTitle = computed(() => this.good?.name);
  childFormVisible = signal<boolean>(false);

  editMode = computed(() => Boolean(this.initialValues) && Boolean(this.orderItemId));
  isGoldMode = computed(() => this.good.pricing_model === 'GOLD');
  isStandardMode = computed(() => this.good.pricing_model === 'STANDARD');

  goldPayload = computed(() =>
    this.isGoldMode() && this.editMode()
      ? (this.initialValues as IPosOrderItem<IGoldPayload>)
      : undefined,
  );
  standardPayload = computed(() =>
    this.isStandardMode() && this.editMode()
      ? (this.initialValues as IPosOrderItem<IStandardPayload>)
      : undefined,
  );

  onChangeTotalAmount = (totalAmount: number) => {
    this.totalAmount.set(totalAmount);
  };

  submit(payload: IPosOrderItem) {
    if (this.editMode()) {
      this.store.editInOrderGoods({ id: this.orderItemId!, good: this.good, ...payload });
    } else {
      this.store.addToInOrderGoods(this.good.id, payload);
    }
    this.close();
  }

  set visible(v: boolean) {
    // call base setter to maintain behavior
    super.visible = v as any;
    if (v) {
      setTimeout(() => this.childFormVisible.set(true), 200);
    } else {
      this.childFormVisible.set(false);
    }
  }
}
