import {
  ChangeDetectionStrategy,
  Component,
  inject,
  computed,
} from '@angular/core';
import { DatePipe } from '@angular/common';
import { CheckoutPrintFacade } from '@isa/checkout/data-access';
import { PrintButtonComponent, Printer } from '@isa/common/print';
import { OrderConfiramtionStore } from '../reward-order-confirmation.store';
import { IfRoleDirective, Role } from '@isa/core/auth';
import { ItemRowDataImports } from '@isa/ui/item-rows';

@Component({
  selector: 'checkout-order-confirmation-header',
  templateUrl: './order-confirmation-header.component.html',
  styleUrls: ['./order-confirmation-header.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [PrintButtonComponent, IfRoleDirective, ItemRowDataImports],
})
export class OrderConfirmationHeaderComponent {
  protected readonly Role = Role;
  #checkoutPrintFacade = inject(CheckoutPrintFacade);
  #store = inject(OrderConfiramtionStore);
  #datePipe = new DatePipe('de-DE');

  orderIds = this.#store.orderIds;

  printFn = (printer: Printer) => {
    return this.#checkoutPrintFacade.printOrderConfirmation({
      printer: printer.key,
      data: this.orderIds() ?? [],
    });
  };

  orderNumbers = computed(() => {
    const orders = this.#store.orders();
    if (!orders || orders.length === 0) {
      return '';
    }
    return orders
      .map((order) => order.orderNumber)
      .filter(Boolean)
      .join('; ');
  });

  orderDates = computed(() => {
    const orders = this.#store.orders();
    if (!orders || orders.length === 0) {
      return '';
    }
    return orders
      .map((order) => {
        if (!order.orderDate) {
          return null;
        }
        const formatted = this.#datePipe.transform(
          order.orderDate,
          'dd.MM.yyyy | HH:mm',
        );
        return formatted ? `${formatted} Uhr` : null;
      })
      .filter(Boolean)
      .join('; ');
  });
}
