import { Maybe } from '@/core';
import { NativeBridgeService } from '@/core/services';
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 { getGoodUnitTypeProperties } from '@/utils';
import { Component, EventEmitter, inject, Input, Output, TemplateRef, ViewChild } from '@angular/core';
import { Badge } from 'primeng/badge';
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,
    Badge,
    Divider,
    ButtonDirective,
    PageDataListComponent,
    TableModule,
    PageLoadingComponent,
    UikitEmptyStateComponent,
    PriceMaskDirective,
  ],
})
export class ConsumerSaleInvoiceSharedComponent {
  private readonly nativeBridge = inject(NativeBridgeService);

  @Input({ required: true }) loading!: boolean;
  @Input() invoice?: Maybe<ISaleInvoiceFullResponse>;
  @Input() variant: TConsumerSaleInvoice = 'full';

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

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

  printInvoice = () => {
    if (this.nativeBridge.isEnabled()) {
      const result = this.nativeBridge.print({
        invoiceId: this.invoice?.id,
        code: this.invoice?.code,
      });
      if (result.success) return;
    }

    window.print();
  };

  columns: IColumn[] = [
    {
      field: '',
      header: '',
      type: 'index',
    },
    {
      field: 'name',
      header: 'عنوان',
      type: 'nested',
      nestedOption: {
        path: 'good.name',
      },
    },
    {
      field: 'unit_price',
      header: 'قیمت واحد',
      type: 'price',
    },
    {
      field: 'quantity',
      header: 'مقدار',
      customDataModel(item) {
        return `${item.quantity} ${getGoodUnitTypeProperties(item.good.unit_type).quantitySymbolText}`;
      },
    },
    {
      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();
  }
}
