import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  output,
  signal,
} from '@angular/core';
import {
  ReceiptItem,
  RemissionResponseArgsErrorMessage,
  RemissionReturnReceiptService,
} from '@isa/remission/data-access';
import { ProductFormatComponent } from '@isa/shared/product-format';
import { ProductImageDirective } from '@isa/shared/product-image';
import { ProductRouterLinkDirective } from '@isa/shared/product-router-link';
import { UiBulletList } from '@isa/ui/bullet-list';
import { productGroupResource } from './resources';
import { IconButtonComponent } from '@isa/ui/buttons';
import { provideIcons } from '@ng-icons/core';
import { isaActionClose } from '@isa/icons';
import { logger } from '@isa/core/logging';
import { injectFeedbackErrorDialog } from '@isa/ui/dialog';
import { firstValueFrom } from 'rxjs';

/**
 * Component for displaying a single receipt item within the remission return receipt details.
 * Shows product information including image, name, and formatted product details.
 *
 * @component
 * @selector remi-remission-return-receipt-details-item
 * @standalone
 *
 * @example
 * <remi-remission-return-receipt-details-item
 *   [item]="receiptItem">
 * </remi-remission-return-receipt-details-item>
 */
@Component({
  selector: 'remi-remission-return-receipt-details-item',
  templateUrl: './remission-return-receipt-details-item.component.html',
  styleUrls: ['./remission-return-receipt-details-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [
    ProductImageDirective,
    ProductRouterLinkDirective,
    ProductFormatComponent,
    UiBulletList,
    IconButtonComponent,
  ],
  providers: [provideIcons({ isaActionClose })],
})
export class RemissionReturnReceiptDetailsItemComponent {
  #logger = logger(() => ({
    component: 'RemissionReturnReceiptDetailsItemComponent',
  }));
  #returnReceiptService = inject(RemissionReturnReceiptService);

  errorDialog = injectFeedbackErrorDialog();

  /**
   * Required input for the receipt item to display.
   * Contains product information and quantity details.
   * @input
   * @required
   */
  item = input.required<ReceiptItem>();

  receiptId = input.required<number>();

  returnId = input.required<number>();

  removeable = input<boolean>(false);

  productGroupResource = productGroupResource();

  productGroupDetail = computed(() => {
    const value = this.productGroupResource.value();
    if (!value) {
      return '';
    }

    return (
      value.find((group) => group.key === this.item().product.productGroup)
        ?.value || ''
    );
  });

  removing = signal(false);

  reloadReturn = output<void>();

  async remove() {
    if (this.removing()) {
      return;
    }
    this.removing.set(true);
    try {
      await this.#returnReceiptService.removeReturnItemFromReturnReceipt({
        receiptId: this.receiptId(),
        returnId: this.returnId(),
        receiptItemId: this.item().id,
      });
    } catch (error) {
      await this.handleRemoveItemError(error);
    }
    this.reloadReturn.emit();
    this.removing.set(false);
  }

  async handleRemoveItemError(error: any) {
    this.#logger.error('Failed to remove item', error);

    const errorMessage =
      error?.error?.message ?? RemissionResponseArgsErrorMessage.AlreadyRemoved;

    await firstValueFrom(
      this.errorDialog({
        data: {
          errorMessage,
        },
      }).closed,
    );
  }
}
