import { DatePipe } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
} from '@angular/core';
import { isaActionChevronDown, isaActionChevronUp } from '@isa/icons';
import {
  Receipt,
  ReceiptListItem,
  ReturnDetailsStore,
} from '@isa/oms/data-access';
import { TextButtonComponent } from '@isa/ui/buttons';
import {
  ExpandableDirective,
  ExpandableTriggerDirective,
  ExpandedDirective,
} from '@isa/ui/expandable';
import { ToolbarComponent } from '@isa/ui/toolbar';
import { NgIcon, provideIcons } from '@ng-icons/core';

export type ReceiptInput =
  | Pick<Receipt, 'id' | 'printedDate' | 'receiptNumber' | 'items'>
  | Pick<ReceiptListItem, 'id' | 'printedDate' | 'receiptNumber' | 'items'>;

@Component({
  selector: 'oms-feature-return-details-order-group',
  templateUrl: './return-details-order-group.component.html',
  styleUrls: ['./return-details-order-group.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [ToolbarComponent, TextButtonComponent, DatePipe, NgIcon],
  providers: [provideIcons({ isaActionChevronDown, isaActionChevronUp })],
})
export class ReturnDetailsOrderGroupComponent {
  #store = inject(ReturnDetailsStore);

  expandableTrigger = inject(ExpandableTriggerDirective, {
    self: true,
    optional: true,
  });

  receipt = input.required<ReceiptInput>();

  receiptId = computed(() => this.receipt().id);

  itemCount = computed(() => {
    const receipt = this.receipt();
    if (typeof receipt.items === 'number') {
      return receipt.items || 0;
    }
    return receipt.items?.length || 0;
  });

  items = this.#store.getItems(this.receiptId);

  selectableItems = this.#store.getSelectableItems(this.receiptId);

  selectOrUnselectAll() {
    const selectableItems = this.selectableItems();

    if (this.allSelected()) {
      this.#store.removeSelectedItems(selectableItems.map((item) => item.id));
    } else {
      this.#store.addSelectedItems(selectableItems.map((item) => item.id));
    }
  }

  allSelected = computed(() => {
    const selectedItemIds = this.#store.selectedItemIds();
    const selectableItems = this.selectableItems();
    return selectableItems.every((item) => {
      return selectedItemIds.includes(item.id);
    });
  });
}
