import { NativeBridgeService } from '@/core/services';
import { ToastService } from '@/core/services/toast.service';
import { PosInfoStore } from '@/domains/pos/store';
import { AbstractDialog } from '@/shared/abstractClasses/abstract-dialog';
import { SharedDialogComponent } from '@/shared/components';
import { formatJalali } from '@/utils';
import { Component, computed, inject, Input, signal } from '@angular/core';
import { Router } from '@angular/router';
import { ButtonDirective } from 'primeng/button';
import { finalize } from 'rxjs';
import { posSaleInvoicesNamedRoutes } from '../../../saleInvoices/constants';
import { PosSaleInvoicesService } from '../../../saleInvoices/services/main.service';
import { IPosOrderResponse } from '../../models';

@Component({
  selector: 'pos-order-submitted-dialog',
  templateUrl: 'order-submitted-dialog.component.html',
  imports: [SharedDialogComponent, ButtonDirective],
})
export class PosOrderSubmittedDialogComponent extends AbstractDialog {
  @Input({ required: true }) invoice!: IPosOrderResponse;
  private readonly nativeBridgeService = inject(NativeBridgeService);
  private readonly service = inject(PosSaleInvoicesService);
  private readonly toastService = inject(ToastService);
  private readonly posInfoStore = inject(PosInfoStore);
  private readonly router = inject(Router);

  readonly posName = computed(() => {
    if (this.posInfoStore.entity()) {
      const { name, businessActivity, complex } = this.posInfoStore.entity()!;
      return `${name} (${businessActivity.name} - ${complex.name})`;
    }
    return '';
  });

  sendingLoading = signal(false);
  sended = signal(false);

  openOrderDetails() {
    this.router.navigateByUrl(
      posSaleInvoicesNamedRoutes.saleInvoice.meta.pagePath!(this.invoice.id),
    );
  }

  sendInvoice() {
    this.sendingLoading.set(true);
    this.service
      .sendToTsp(this.invoice.id)
      .pipe(finalize(() => this.sendingLoading.set(false)))
      .subscribe(() => {
        this.toastService.success({ text: 'ارسال فاکتور با موفقیت انجام شد.' });
        this.sended.set(true);
      });
  }

  printInvoice() {
    const printResult = this.nativeBridgeService.print([
      {
        title: `فروشگاه ${this.posName()}`,
        items: [
          {
            label: 'شماره فاکتور',
            value: this.invoice.code,
          },
          { label: 'تاریخ', value: formatJalali(this.invoice.invoice_date, 'YYYY/MM/DD') },
          { label: 'مبلغ کل', value: this.invoice.total_amount },
        ],
      },
    ]);
  }

  sendToTsp() {}
}
