import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  output,
  Signal,
  ViewEncapsulation,
} from '@angular/core';
import { isaActionCheck, isaActionPrinter } from '@isa/icons';
import {
  Product,
  ReceiptItemTaskListItem,
  TaskActionType,
  TaskActionTypeType,
} from '@isa/oms/data-access';
import { ReturnProductInfoComponent } from '@isa/oms/shared/product-info';
import { ButtonComponent, InfoButtonComponent } from '@isa/ui/buttons';
import { NgIconComponent, provideIcons } from '@ng-icons/core';

@Component({
  selector: 'oms-shared-return-task-list-item',
  templateUrl: './return-task-list-item.component.html',
  styleUrl: './return-task-list-item.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [
    ReturnProductInfoComponent,
    ButtonComponent,
    NgIconComponent,
    InfoButtonComponent,
  ],
  providers: [provideIcons({ isaActionCheck, isaActionPrinter })],
  host: {
    '[class]': "['oms-shared-return-task-list-item', appearanceClass()]",
  },
  encapsulation: ViewEncapsulation.None,
})
export class ReturnTaskListItemComponent {
  appearance = input<'main' | 'review'>('main');
  item = input.required<ReceiptItemTaskListItem>();
  action = output<TaskActionType>();

  appearanceClass = computed(
    () => `oms-shared-return-task-list-item__${this.appearance()}`,
  );

  product = computed(() => {
    const item = this.item();
    const product = item.product;

    if (product) {
      return product as Product;
    }

    return undefined;
  });

  processingComment = computed(() => {
    const item = this.item();
    const processingComment = item.processingComment;

    if (processingComment) {
      return processingComment;
    }

    return undefined;
  });

  displayPrintTolino = computed(() => {
    const item = this.item();
    return item?.actions?.some(
      (keyValue) => keyValue.key === 'PRINT_TOLINO_RETURN_RECEIPT',
    );
  });

  type: Signal<TaskActionTypeType> = computed(() => {
    const item = this.item();
    const mappedType: Omit<TaskActionType, 'taskId'> = {
      type: item.type as TaskActionTypeType,
    };
    return mappedType.type;
  });

  onActionClick(type: Omit<TaskActionType, 'taskId'>) {
    const taskId = this.item().id;
    const receiptItemId = this.item()?.receiptItem?.id;
    const actionType: TaskActionType = {
      taskId,
      receiptItemId,
      type: type.type,
      updateTo: type?.updateTo,
      actions: type?.actions,
    };
    this.action.emit(actionType);
  }
}
