import { NativeBridgeService } from '@/core/services';
import { ToastService } from '@/core/services/toast.service';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { InputComponent, KeyValueComponent } from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, computed, inject, signal } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { ButtonDirective } from 'primeng/button';
import { catchError, throwError } from 'rxjs';
import { IPayment, TOrderPaymentTypes } from '../../models';
import { PosLandingStore } from '../../store/main.store';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';

@Component({
  selector: 'pos-payment-form-dialog',
  templateUrl: './form-dialog.component.html',
  imports: [
    ReactiveFormsModule,
    InputComponent,
    FormFooterActionsComponent,
    KeyValueComponent,
    ButtonDirective,
    SharedDialogComponent,
  ],
})
export class PosPaymentFormDialogComponent extends AbstractFormDialog<IPayment, IPayment> {
  private readonly store = inject(PosLandingStore);
  private readonly nativeBridge = inject(NativeBridgeService);
  private readonly toastServices = inject(ToastService);

  readonly totalAmount = computed(() => this.store.orderPricingInfo().totalAmount);

  readonly remainedAmount = signal(this.totalAmount());
  setOffMax = signal(this.remainedAmount());
  cashMax = signal(this.remainedAmount());
  terminalMax = signal(this.remainedAmount());

  submitOrderLoading = computed(() => this.store.submitOrderLoading());

  private initForm = () => {
    const form = this.fb.group({
      set_off: [this.initialValues?.set_off || 0],
      cash: [this.initialValues?.cash || 0],
      terminal: [this.initialValues?.terminal || 0],
    });

    form.valueChanges.subscribe((value) => {
      const totalValue = (value.cash || 0) + (value.set_off || 0) + (value.terminal || 0);
      const remainedAmount = this.totalAmount() - totalValue;

      const setOffMax = remainedAmount + (value.set_off || 0);
      const cashMax = remainedAmount + (value.cash || 0);
      const terminalMax = remainedAmount + (value.terminal || 0);

      form.controls.set_off.clearValidators();
      form.controls.set_off.addValidators([Validators.max(setOffMax)]);
      form.controls.cash.clearValidators();
      form.controls.cash.addValidators([Validators.max(cashMax)]);
      form.controls.terminal.clearValidators();
      form.controls.terminal.addValidators([Validators.max(terminalMax)]);

      this.remainedAmount.set(remainedAmount);
      this.cashMax.set(cashMax);
      this.terminalMax.set(terminalMax);
      this.setOffMax.set(setOffMax);
    });

    return form;
  };

  form = this.initForm();

  fillRemained(type: TOrderPaymentTypes) {
    switch (type) {
      case 'TERMINAL':
        this.form.controls.terminal.setValue(
          (this.form.controls.terminal.value || 0) + this.remainedAmount(),
        );
        break;

      case 'CASH':
        this.form.controls.cash.setValue(
          (this.form.controls.cash.value || 0) + this.remainedAmount(),
        );
        break;

      case 'SET_OFF':
        this.form.controls.set_off.setValue(
          (this.form.controls.set_off.value || 0) + this.remainedAmount(),
        );
        break;
    }
  }

  override showSuccessMessage = false;

  override submitForm() {
    if (this.remainedAmount() > 0) {
      return this.toastServices.warn({
        text: 'فاکتور تسویه نشده است. لطفا مبلغ پرداخت را کامل کنید..',
      });
    }

    const payment = this.form.value as IPayment;

    if (payment.terminal > 0 && this.nativeBridge.isEnabled()) {
      const payResult = this.nativeBridge.pay({
        amount: payment.terminal,
        totalAmount: this.totalAmount(),
        invoiceDate: new Date().toISOString(),
      });

      if (!payResult.success) {
        return this.toastServices.warn({
          text: payResult.error || 'پرداخت با دستگاه انجام نشد. لطفا دوباره تلاش کنید.',
        });
      }
    }

    this.store.setPayment(payment);

    this.store
      .submitOrder()
      .pipe(
        catchError((err) => {
          return throwError(() => err);
        }),
      )
      .subscribe((res) => {
        if (this.nativeBridge.isEnabled()) {
          this.nativeBridge.print({
            invoiceId: res?.id,
            code: res?.code,
          });
        }
        this.close();
        this.toastServices.success({
          text: 'فاکتور شما با موفقیت ایجاد شد',
        });
      });
  }

  override onSuccess(response: IPayment): void {}
}
