import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { CdkMenuModule } from '@angular/cdk/menu';
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { RouterLink } from '@angular/router';
import { ComponentStore } from '@ngrx/component-store';
import { IconComponent } from '@shared/components/icon';
import { SharedMenuModule } from '@shared/components/menu';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { CustomerInfoDTO } from '@generated/swagger/crm-api';
import { MatomoModule } from 'ngx-matomo-client';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

export interface PickUpShelfDetailsHeaderNavMenuComponentState {
  customer?: CustomerInfoDTO;
  showCustomerDetails: boolean;
}

@Component({
  selector: 'page-pickup-shelf-details-header-nav-menu',
  templateUrl: 'pickup-shelf-details-header-nav-menu.component.html',
  styleUrls: ['pickup-shelf-details-header-nav-menu.component.scss'],
  host: { class: 'page-pickup-shelf-details-header-nav-menu' },
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CdkMenuModule, SharedMenuModule, IconComponent, RouterLink, AsyncPipe, MatomoModule],
})
export class PickUpShelfDetailsHeaderNavMenuComponent extends ComponentStore<PickUpShelfDetailsHeaderNavMenuComponentState> {
  @Input() set customer(value: CustomerInfoDTO) {
    this.patchState({ customer: value });
  }

  @Input() set showCustomerDetails(value: BooleanInput) {
    this.patchState({ showCustomerDetails: coerceBooleanProperty(value) });
  }

  readonly customer$ = this.select((state) => state.customer);

  readonly showCustomerDetails$ = this.select((state) => state.showCustomerDetails);

  ordersRoute$ = this.customer$.pipe(
    map(
      (customer) =>
        !!customer && this._navigation.ordersRoute({ processId: Date.now(), customerId: customer?.id, customer }),
    ),
  );

  customerDetailsRoute$ = combineLatest([this.showCustomerDetails$, this.customer$]).pipe(
    map(
      ([showCustomerDetails, customer]) =>
        showCustomerDetails &&
        !!customer &&
        this._navigation.detailsRoute({ processId: Date.now(), customerId: customer?.id, customer }),
    ),
  );

  constructor(private _navigation: CustomerSearchNavigation) {
    super({
      showCustomerDetails: true,
    });
  }
}
