import { AbstractForm } from '@/shared/abstractClasses';
import { InputComponent } from '@/shared/components';
import { AmountPercentageInputComponent } from '@/shared/components/amountPercentageInput/amount-percentage-input.component';
import { formatWithCurrency, getGoodUnitTypeProperties, UnitType } 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 { Button } from 'primeng/button';
import { debounceTime } from 'rxjs/operators';
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,
    Button,
    PosFormDialogAmountCardTemplateComponent,
    AmountPercentageInputComponent,
  ],
})
export class PosStandardPayloadFormComponent extends AbstractForm<
  IPosOrderItem<IStandardPayload>,
  IPosOrderItem<IStandardPayload>
> {
  @Input({ required: true }) unitType!: UnitType;
  @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(debounceTime(100), takeUntilDestroyed()).subscribe((value) => {
      this.updateCalculateAmount(value as Partial<IPosOrderItem<IStandardPayload>>);
    });

    return form;
  };

  form = this.initialForm();
  @Input() set visibleForm(v: boolean) {
    if (v && this.editMode) {
      this.form.patchValue(this.initialValues || {}, { emitEvent: false });
      this.updateCalculateAmount(this.form.value as Partial<IPosOrderItem<IStandardPayload>>);
    }
  }
  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(),
    });
  }

  preparedFormVisuals = computed(() => getGoodUnitTypeProperties(this.unitType));

  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 * 0.1;

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