import {
  Component,
  ChangeDetectionStrategy,
  inject,
  input,
  effect,
  computed,
  output,
} from '@angular/core';
import { DatePipe, DecimalPipe } from '@angular/common';
import { CdkTableModule } from '@angular/cdk/table';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import {
  isaActionPolygonUp,
  isaActionPolygonDown,
  isaActionRefresh,
} from '@isa/icons';
import { logger } from '@isa/core/logging';
import { EmptyStateComponent } from '@isa/ui/empty-state';
import { CustomerCardTransactionsResource } from '@isa/crm/data-access';
import { LoyaltyBookingInfoDTO } from '@generated/swagger/crm-api';
import { IconButtonComponent } from '@isa/ui/buttons';

@Component({
  selector: 'crm-customer-card-transactions',
  imports: [
    DatePipe,
    DecimalPipe,
    CdkTableModule,
    NgIconComponent,
    EmptyStateComponent,
    IconButtonComponent,
  ],
  providers: [
    provideIcons({
      isaActionPolygonUp,
      isaActionPolygonDown,
      isaActionRefresh,
    }),
  ],
  templateUrl: './crm-feature-customer-card-transactions.component.html',
  styleUrl: './crm-feature-customer-card-transactions.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CrmFeatureCustomerCardTransactionsComponent {
  readonly #logger = logger(() => ({
    component: 'CrmFeatureCustomerCardTransactionsComponent',
  }));
  readonly #transactionsResource = inject(CustomerCardTransactionsResource);

  /**
   * Card code to load transactions for.
   * Should be the code of the first activated card.
   */
  readonly customerId = input<number | undefined>(undefined);

  readonly reload = output<void>();

  /**
   * Exposed resource signals for template
   */
  readonly transactions = this.#transactionsResource.resource.value;
  readonly isLoading = this.#transactionsResource.resource.isLoading;
  readonly error = this.#transactionsResource.resource.error;

  /**
   * Data source for CDK table - defaults to empty array when undefined
   */
  readonly dataSource = computed(() => this.transactions()?.slice(0, 50) ?? []);

  /**
   * Column definitions for the table
   */
  readonly displayedColumns: Array<keyof LoyaltyBookingInfoDTO> = [
    'date',
    'reason',
    'amount',
    'reference',
    'points',
  ];

  /**
   * Track by function for performance
   */
  readonly trackByDate = (_index: number, item: { date: Date }) => item.date;

  constructor() {
    // React to customerId input changes
    effect(() => {
      const customerId = this.customerId();
      this.#logger.debug('CustomerId changed', () => ({ customerId }));
      this.#transactionsResource.params({ customerId });
    });
  }

  /**
   * Emits reload event to notify parent component.
   * Parent is responsible for reloading resources to coordinate multi-resource updates.
   */
  refresh() {
    this.reload.emit();
  }
}
