import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  signal,
} from '@angular/core';
import { ReturnSummaryItemComponent } from './return-summary-item/return-summary-item.component';
import { injectTabId } from '@isa/core/tabs';
import {
  ReturnProcess,
  ReturnProcessService,
  ReturnProcessStore,
} from '@isa/oms/data-access';
import { ButtonComponent } from '@isa/ui/buttons';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { Location } from '@angular/common';
import { isaActionChevronLeft } from '@isa/icons';
import { logger } from '@isa/core/logging';
import { ActivatedRoute, Router } from '@angular/router';

/**
 * Main component for the return summary feature. Displays a list of items being returned
 * and allows users to review and confirm the return process.
 *
 * Uses:
 * - ReturnProcessStore: Manages return process state
 * - ReturnProcessService: Handles return process business logic
 * - Location: For navigation
 * - Logger: For error tracking
 *
 * @example
 * ```html
 * <oms-feature-return-summary></oms-feature-return-summary>
 * ```
 */
@Component({
  selector: 'oms-feature-return-summary',
  templateUrl: './return-summary.component.html',
  styleUrls: ['./return-summary.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReturnSummaryItemComponent, ButtonComponent, NgIcon],
  providers: [provideIcons({ isaActionChevronLeft })],
})
export class ReturnSummaryComponent {
  #logger = logger(() => ({ component: ReturnSummaryComponent }));

  #returnProcessStore = inject(ReturnProcessStore);
  #returnProcessService = inject(ReturnProcessService);

  #router = inject(Router);
  #activatedRoute = inject(ActivatedRoute);

  /** Angular Location service for navigation */
  location = inject(Location);

  /** The active process ID from the current route */
  processId = injectTabId();

  /** Filtered list of return processes for the current process ID */
  returnProcesses = computed<ReturnProcess[]>(() => {
    const processId = this.processId();
    return this.#returnProcessStore
      .entities()
      .filter((p) => p.processId === processId);
  });

  /**
   * Signal tracking the current status of the return and print operation.
   * Possible values:
   * - undefined: Initial state, no operation started
   * - 'pending': Operation in progress
   * - 'success': Operation completed successfully
   * - 'error': Operation failed
   */
  returnItemsAndPrintReciptStatus = signal<
    undefined | 'pending' | 'success' | 'error'
  >(undefined);

  /**
   * Computed signal to determine if the return items and print receipt operation is pending.
   *
   * This signal checks the current status of the returnItemsAndPrintReciptStatus signal
   * and returns true if the status is 'pending', otherwise false.
   *
   * @returns {boolean} True if the operation is pending, false otherwise
   */
  returnItemsAndPrintReciptStatusPending = computed(() => {
    return this.returnItemsAndPrintReciptStatus() === 'pending';
  });
  /**
   * 1. Checks if a return process is already in progress
   * 2. Sets status to pending while processing
   * 3. Calls the ReturnProcessService to complete the return
   * 4. Updates status based on success/failure
   * 5. Logs errors if they occur
   *
   * The button will be disabled and show a loading indicator while processing,
   * and will be hidden after a successful return.
   *
   * @returns {Promise<void>}
   */
  async returnItemsAndPrintRecipt() {
    if (this.returnItemsAndPrintReciptStatus() === 'pending') {
      this.#logger.warn('Return process already in progress', () => ({
        function: 'returnItemsAndPrintRecipt',
      }));
      return;
    }

    try {
      this.returnItemsAndPrintReciptStatus.set('pending');

      const returnReceipts =
        await this.#returnProcessService.completeReturnProcess(
          this.returnProcesses(),
        );

      this.#logger.info('Return receipts created', () => ({
        count: returnReceipts.length,
      }));
      this.returnItemsAndPrintReciptStatus.set('success');

      this.#returnProcessStore.finishProcess(returnReceipts);
      await this.#router.navigate(['../', 'review'], {
        relativeTo: this.#activatedRoute,
      });
    } catch (error) {
      this.#logger.error(
        'Error completing return process',
        error as Error,
        () => ({
          function: 'returnItemsAndPrintRecipt',
        }),
      );
      this.returnItemsAndPrintReciptStatus.set('error');
    }
  }
}
