import { ToastService } from '@/core/services/toast.service';
import { CatalogTaxProviderStatusTagComponent } from '@/shared/catalog/taxProviderStatus';
import { KeyValueComponent } from '@/shared/components';
import { Component, computed, EventEmitter, inject, Input, Output, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Button, ButtonDirective } from 'primeng/button';
import { Card } from 'primeng/card';
import { finalize } from 'rxjs';
import { posSaleInvoicesNamedRoutes } from '../constants';
import { IPosSaleInvoicesSummaryResponse } from '../models';
import { PosSaleInvoicesService } from '../services/main.service';

@Component({
  selector: 'pos-saleInvoice-card',
  templateUrl: './sale-invoice-card.component.html',
  imports: [
    Button,
    KeyValueComponent,
    Card,
    RouterLink,
    ButtonDirective,
    CatalogTaxProviderStatusTagComponent,
  ],
})
export class SaleInvoiceCardComponent {
  private readonly service = inject(PosSaleInvoicesService);
  private readonly toastService = inject(ToastService);

  @Input({ required: true }) saleInvoice!: IPosSaleInvoicesSummaryResponse;
  @Output() refreshRequested = new EventEmitter<void>();

  sendingLoading = signal(false);
  gettingStatusLoading = signal(false);
  resendingLoading = signal(false);
  revokingInvoiceLoading = signal(false);

  onAction = computed(
    () =>
      this.sendingLoading() ||
      this.gettingStatusLoading() ||
      this.resendingLoading() ||
      this.revokingInvoiceLoading(),
  );

  singlePageRoute = computed(() =>
    posSaleInvoicesNamedRoutes.saleInvoice.meta.pagePath!(this.saleInvoice?.id),
  );
  preparedInvoiceType = computed(() => {
    if (!this.saleInvoice) return '';
    const { customer } = this.saleInvoice;

    if (customer) {
      const { legal, individual } = customer;
      let text = 'نوع اول - ';
      if (legal) {
        text += `حقوقی (${legal.company_name})`;
      }
      if (individual) {
        text += `حقیقی (${individual.first_name} ${individual.last_name})`;
      }
      return text;
    }
    return 'نوع دوم (بدون اطلاعات خریدار)';
  });

  sendInvoice() {
    this.sendingLoading.set(true);
    this.service
      .sendToTsp(this.saleInvoice.id)
      .pipe(finalize(() => this.sendingLoading.set(false)))
      .subscribe((res) => {
        if (res.status === 'FAILURE') {
          this.toastService.error({
            text: res.message || 'خطا در ارسال فاکتور رخ داده است.',
          });
        } else {
          this.toastService.success({ text: 'ارسال فاکتور با موفقیت انجام شد.' });
        }
        this.toastService.success({ text: 'ارسال فاکتور با موفقیت انجام شد.' });
        this.refreshRequested.emit();
      });
  }

  getStatus() {
    this.gettingStatusLoading.set(true);
    this.service
      .getInquiry(this.saleInvoice.id)
      .pipe(finalize(() => this.gettingStatusLoading.set(false)))
      .subscribe((res) => {
        this.refreshRequested.emit();
      });
  }

  resendInvoice() {
    this.resendingLoading.set(true);
    this.service
      .retrySendToTsp(this.saleInvoice.id)
      .pipe(finalize(() => this.resendingLoading.set(false)))
      .subscribe((res) => {
        if (res.status === 'FAILURE') {
          this.toastService.error({ text: res.message || 'خطا در ارسال مجدد فاکتور رخ داده است.' });
        } else {
          this.toastService.success({ text: 'ارسال مجدد فاکتور با موفقیت انجام شد.' });
        }
        this.refreshRequested.emit();
      });
  }

  revokeInvoice() {
    this.revokingInvoiceLoading.set(true);
    this.service
      .revoke(this.saleInvoice.id)
      .pipe(finalize(() => this.revokingInvoiceLoading.set(false)))
      .subscribe(() => {
        this.toastService.success({ text: 'ابطال فاکتور با موفقیت انجام شد.' });
        this.refreshRequested.emit();
      });
  }
  viewDetails() {}
}
