import { Maybe } from '@/core';
import { NativeBridgeService } from '@/core/services';
import { ToastService } from '@/core/services/toast.service';
import { PosInfoStore } from '@/domains/pos/store';
import { CatalogTaxProviderStatusTagComponent } from '@/shared/catalog';
import { AppCardComponent, KeyValueComponent } from '@/shared/components';
import { ISaleInvoiceFullResponse } from '@/shared/components/invoices/sale-invoice-full-response.model';
import { PageLoadingComponent } from '@/shared/components/page-loading.component';
import {
  IColumn,
  PageDataListComponent,
} from '@/shared/components/pageDataList/page-data-list.component';
import { PriceMaskDirective } from '@/shared/directives';
import { UikitEmptyStateComponent } from '@/uikit';
import {
  Component,
  computed,
  EventEmitter,
  inject,
  Input,
  Output,
  TemplateRef,
  ViewChild,
} from '@angular/core';
import { UrlTree } from '@angular/router';
import { ButtonDirective } from 'primeng/button';
import { Divider } from 'primeng/divider';
import { TableModule } from 'primeng/table';

export type TSaleInvoiceSingleViewVariant = 'full' | 'customer' | 'pos';

@Component({
  selector: 'shared-sale-invoice-single-view',
  templateUrl: './sale-invoice-single-view.component.html',
  imports: [
    AppCardComponent,
    KeyValueComponent,
    Divider,
    ButtonDirective,
    PageDataListComponent,
    TableModule,
    PageLoadingComponent,
    UikitEmptyStateComponent,
    PriceMaskDirective,
    CatalogTaxProviderStatusTagComponent,
  ],
})
export class SharedSaleInvoiceSingleViewComponent {
  private readonly nativeBridge = inject(NativeBridgeService);
  private readonly posInfoStore = inject(PosInfoStore);
  private readonly toastService = inject(ToastService);

  @Input({ required: true }) loading!: boolean;
  @Input() invoice!: Maybe<ISaleInvoiceFullResponse>;
  @Input() variant: TSaleInvoiceSingleViewVariant = 'full';
  @Input() backRoute?: UrlTree | string | any[];

  @Output() onRefresh = new EventEmitter<void>();

  @ViewChild('totalAmount', { static: false }) totalAmount!: TemplateRef<any>;

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

  printInvoice = () => {
    try {
      if (this.invoice) {
        this.nativeBridge.print([
          {
            title: 'اطلاعات صورت‌حساب',
            items: [
              {
                label: 'شماره منحصر به فرد مالیاتی',
                value: 'this.invoice',
              },
              {
                label: 'شماره صورت‌حساب',
                value: this.invoice.code,
              },
              {
                label: 'موضوع صورت‌حساب',
                value: 'this.invoice',
              },
              {
                label: 'نوع صورت‌حساب',
                value: 'this.invoice',
              },
              {
                label: 'تاریخ و ساعت',
                value: this.invoice.invoice_date,
              },
              {
                label: 'وضعیت صورت‌حساب مالیاتی',
                value: this.invoice.status.translate,
              },
            ],
          },
          {
            title: `اطلاعات فروشنده`,
            items: [
              {
                label: 'عنوان فروشگاه',
                value: this.invoice.pos.complex.business_activity.name,
              },
              {
                label: 'عنوان شعبه',
                value: this.invoice.pos.complex.name,
              },
              {
                label: 'عنوان پایانه‌ فروش',
                value: this.invoice.pos.name,
              },
              {
                label: 'شماره اقتصادی',
                value: 'this.invoice.pos.complex.business_activity.economic_code',
              },
            ],
          },
          {
            title: `اطلاعات خریدار`,
            items: [
              {
                label: 'نام خریدار',
                value:
                  (this.invoice.customer
                    ? this.invoice.customer.type === 'LEGAL'
                      ? this.invoice.customer.legal?.company_name
                      : `${this.invoice.customer.individual?.first_name} ${this.invoice.customer.individual?.last_name}`
                    : this.invoice.unknown_customer?.name) || '-',
              },
              {
                label: 'شماره اقتصادی',
                value:
                  (this.invoice.customer
                    ? this.invoice.customer.type === 'LEGAL'
                      ? this.invoice.customer.legal?.economic_code
                      : this.invoice.customer.individual?.economic_code || '-'
                    : '-') || '-',
              },
            ],
          },
        ]);
      }
    } catch (error) {
      return this.toastService.error({
        text: 'چاپ صورت‌حساب با خطا مواجه شد. لطفا دوباره تلاش کنید.',
      });
    }
  };

  columns: IColumn[] = [
    {
      field: 'name',
      header: 'عنوان',
      type: 'nested',
      nestedOption: {
        path: 'good.name',
      },
    },
    {
      field: 'sku_code',
      header: 'شناسه کالا',
    },
    {
      field: 'unit_price',
      header: 'قیمت واحد',
      type: 'price',
    },
    {
      field: 'quantity',
      header: 'مقدار',
      customDataModel(item) {
        return `${item.quantity} ${item.measure_unit_text}`;
      },
    },
    {
      field: 'total_amount',
      header: 'قیمت نهایی',
      type: 'price',
    },
  ];

  expandableColumns: IColumn[] = [
    {
      field: 'commission',
      header: 'کارمزد',
      type: 'price',
    },
    {
      field: 'wages',
      header: 'اجرت',
      type: 'price',
    },
    {
      field: 'profit',
      header: 'سود',
      type: 'price',
    },
  ];

  expandedRows: { [key: string]: boolean } = {};

  refresh() {
    this.onRefresh.emit();
  }
}
