import { ChangeDetectionStrategy, Component, Input, ElementRef } from '@angular/core';
import { ApplicationService } from '@core/application';
import { EnvironmentService } from '@core/environment';
import { ComponentStore } from '@ngrx/component-store';
import { OrderItemListItemDTO } from '@generated/swagger/oms-api';
import { isEqual } from 'lodash';
import { CustomerOrderSearchStore } from '../customer-order-search.store';
import { CustomerOrdersNavigationService } from '@shared/services/navigation';
import { map } from 'rxjs/operators';

export interface CustomerOrderItemComponentState {
  item?: OrderItemListItemDTO;
}

@Component({
  selector: 'page-customer-order-item',
  templateUrl: 'customer-order-item.component.html',
  styleUrls: ['customer-order-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class CustomerOrderItemComponent extends ComponentStore<CustomerOrderItemComponentState> {
  @Input()
  get item() {
    return this.get((s) => s.item);
  }
  set item(item: OrderItemListItemDTO) {
    if (!isEqual(this.item, item)) {
      this.patchState({ item });
    }
  }

  readonly item$ = this.select((s) => s.item);

  get isTablet() {
    return this._environment.matchTablet();
  }

  get isDesktopLarge() {
    return this._environment.matchDesktopLarge();
  }

  get queryParams() {
    const compartmentCode = this.item?.compartmentCode;
    const queryParams = this._customerOrderStore.filter?.getQueryParams();
    if (compartmentCode) {
      return {
        ...queryParams,
        buyerNumber: this.item?.buyerNumber,
      };
    } else {
      return {
        ...queryParams,
      };
    }
  }

  get detailsLink() {
    const orderId = this.item?.orderId;
    const processingStatus = this.item?.processingStatus;
    const compartmentCode = this.item?.compartmentCode;
    return this._navigationService.getCustomerOrdersDetailsPath({
      processId: this._applicationService.activatedProcessId,
      processingStatus,
      compartmentCode: compartmentCode ? encodeURIComponent(compartmentCode) : undefined,
      orderId: orderId ? orderId : undefined,
    }).path;
  }

  @Input()
  primaryOutletActive?: boolean = false;

  showChangeDate$ = this.item$.pipe(map((item) => [256, 512, 1024, 2048, 4069].includes(item?.processingStatus)));

  constructor(
    private _environment: EnvironmentService,
    private _customerOrderStore: CustomerOrderSearchStore,
    private _navigationService: CustomerOrdersNavigationService,
    private _applicationService: ApplicationService,
    private _elRef: ElementRef,
  ) {
    super({});
  }

  scrollIntoView() {
    this._elRef.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
}
