import { DatePipe } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  linkedSignal,
} from '@angular/core';
import {
  getPackageNumbersFromReturn,
  getReceiptItemQuantityFromReturn,
  getReceiptNumberFromReturn,
  getReceiptStatusFromReturn,
  ReceiptCompleteStatusValue,
  Return,
} from '@isa/remission/data-access';
import { SkeletonLoaderDirective } from '@isa/ui/skeleton-loader';
import { createSupplierResource } from './resources';

@Component({
  selector: 'remi-remission-return-receipt-details-card',
  templateUrl: './remission-return-receipt-details-card.component.html',
  styleUrls: ['./remission-return-receipt-details-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [SkeletonLoaderDirective, DatePipe],
})
export class RemissionReturnReceiptDetailsCardComponent {
  /**
   * Input for the return data to be displayed in the card.
   * @input
   */
  return = input.required<Return>();

  /**
   * Input to control the loading state of the card.
   * @input
   * @default true
   */
  loading = input(true);

  /**
   * Resource for fetching supplier data.
   */
  supplierResource = createSupplierResource();

  firstReceipt = computed(() => {
    const returnData = this.return();
    return returnData?.receipts?.[0]?.data;
  });

  /**
   * Computed signal that retrieves the receipt number from the return data.
   * Uses the helper function to get the receipt number.
   * @returns {string} The receipt number from the return
   */
  receiptNumber = computed(() => {
    const returnData = this.return();
    return getReceiptNumberFromReturn(returnData);
  });

  /**
   * Computed signal that calculates the total item quantity from all receipts in the return.
   * Uses the helper function to get the quantity.
   * @returns {number} The total item quantity from all receipts
   */
  itemQuantity = computed(() => {
    const returnData = this.return();
    return getReceiptItemQuantityFromReturn(returnData);
  });

  /**
   * Linked signal that determines the completion status of the return.
   * Uses the helper function to get the status based on the return data.
   * @returns {ReceiptCompleteStatusValue} The completion status of the return
   */
  status = linkedSignal<ReceiptCompleteStatusValue>(() => {
    const returnData = this.return();
    return getReceiptStatusFromReturn(returnData);
  });

  remiDate = computed(() => {
    const returnData = this.return();
    return returnData?.completed || returnData?.created;
  });

  packageNumber = computed(() => {
    const returnData = this.return();
    return getPackageNumbersFromReturn(returnData);
  });

  supplier = computed(() => {
    const receipt = this.firstReceipt();
    const supplier = this.supplierResource.value();

    return (
      supplier?.find((s) => s.id === receipt?.supplier?.id)?.name || 'Unbekannt'
    );
  });
}
