import { Maybe } from '@/core';
import { NativeBridgeService } from '@/core/services';
import { PosInfoStore } from '@/domains/pos/store';
import { CatalogTaxProviderStatusTagComponent } from '@/shared/catalog';
import { AppCardComponent, KeyValueComponent } from '@/shared/components';
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 { formatJalali } from '@/utils';
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';
import { ISaleInvoiceFullResponse } from '../../models';

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

@Component({
  selector: 'consumer-saleInvoice-shared',
  templateUrl: './shared-saleInvoice.component.html',
  imports: [
    AppCardComponent,
    KeyValueComponent,
    Divider,
    ButtonDirective,
    PageDataListComponent,
    TableModule,
    PageLoadingComponent,
    UikitEmptyStateComponent,
    PriceMaskDirective,
    CatalogTaxProviderStatusTagComponent,
  ],
})
export class ConsumerSaleInvoiceSharedComponent {
  private readonly nativeBridge = inject(NativeBridgeService);

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

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

  @ViewChild('totalAmount', { static: false }) totalAmount!: TemplateRef<any>;
  private readonly posInfoStore = inject(PosInfoStore);

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

  printInvoice = () => {
    if (this.invoice) {
      const printResult = this.nativeBridge.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 },
          ],
        },
      ]);
    }
  };

  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',
      // customDataModel: this.totalAmount,
    },
  ];

  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();
  }
}
