import ISummary from '@/core/models/summary';
import { AbstractForm } from '@/shared/abstractClasses';
import { InputComponent } from '@/shared/components';
import { AmountPercentageInputComponent } from '@/shared/components/amountPercentageInput/amount-percentage-input.component';
import { formatWithCurrency } from '@/utils';
import { Component, computed, EventEmitter, Input, Output, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { ButtonDirective } from 'primeng/button';
import { IPosOrderItem, IStandardPayload } from '../../../models';
import { PosFormDialogAmountCardTemplateComponent } from '../form-dialog-amount-card-template.component';

@Component({
  selector: 'pos-standard-payload-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    InputComponent,
    PosFormDialogAmountCardTemplateComponent,
    AmountPercentageInputComponent,
    ButtonDirective,
  ],
})
export class PosStandardPayloadFormComponent extends AbstractForm<
  IPosOrderItem<IStandardPayload>,
  IPosOrderItem<IStandardPayload>
> {
  @Input({ required: true }) measureUnit!: ISummary;
  @Input({ required: true }) vatPercentage!: number;
  @Output() onChangeTotalAmount = new EventEmitter<number>();

  private readonly initialForm = () => {
    const form = this.fb.group({
      unit_price: [this.initialValues?.unit_price || 0, [Validators.required]],
      quantity: [this.initialValues?.quantity || 0, [Validators.required]],
      discount_amount: [this.initialValues?.discount || 0, [Validators.min(0)]],
      discount_percentage: [0, [Validators.min(0), Validators.max(100)]],
    });

    form.valueChanges.pipe(takeUntilDestroyed()).subscribe((value) => {
      this.updateCalculateAmount(value as Partial<IPosOrderItem<IStandardPayload>>);
    });

    return form;
  };

  form = this.initialForm();
  override submitForm(payload: IPosOrderItem<IStandardPayload>) {
    this.onSubmit.emit({
      ...payload,
      total_amount: this.totalAmount(),
      discount_amount: this.discountAmount(),
      tax_amount: this.taxAmount(),
      base_total_amount: this.baseTotalAmount(),
    });
  }

  baseTotalAmount = signal<number>(0);
  totalAmount = signal<number>(0);
  discountAmount = signal<number>(0);
  taxAmount = signal<number>(0);

  preparedCTAText = computed(() => (this.editMode ? 'اعمال ویرایش' : 'افزودن به لیست خرید'));

  toPriceFormat(amount: number) {
    if (!amount) {
      return '';
    }
    return `(${formatWithCurrency(amount)})`;
  }

  updateCalculateAmount(value: Partial<IPosOrderItem<IStandardPayload>>) {
    const baseTotalAmount = (value.unit_price ?? 0) * (value.quantity ?? 0);
    const discountAmount = Number(value.discount_amount ?? '0');
    const baseTotalAmountWithoutTax = baseTotalAmount - discountAmount;
    const taxAmount = baseTotalAmountWithoutTax * this.vatPercentage;

    this.baseTotalAmount.set(baseTotalAmount);
    this.discountAmount.set(discountAmount);
    this.taxAmount.set(taxAmount);
    this.totalAmount.set(baseTotalAmountWithoutTax + taxAmount);
  }
}
