import { Component, ChangeDetectionStrategy, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Observable, Subject } from 'rxjs';
import { map, takeUntil, withLatestFrom } from 'rxjs/operators';
import { CustomerOrderSearchStore } from './customer-order-search.store';
import { CustomerOrderSearchMainAutocompleteProvider } from './providers/customer-order-search-main-autocomplete.provider';
import { EnvironmentService } from '@core/environment';
import { FilterAutocompleteProvider } from '@shared/components/filter';
import { CustomerOrdersNavigationService } from '@shared/services/navigation';

@Component({
  selector: 'page-customer-order-search',
  templateUrl: 'customer-order-search.component.html',
  styleUrls: ['customer-order-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: FilterAutocompleteProvider,
      useClass: CustomerOrderSearchMainAutocompleteProvider,
      multi: true,
    },
  ],
  standalone: false,
})
export class CustomerOrderSearchComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject<void>();
  private _processId$: Observable<number>;

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

  constructor(
    private _customerOrdersSearchStore: CustomerOrderSearchStore,
    private _navigationService: CustomerOrdersNavigationService,
    private _breadcrumb: BreadcrumbService,
    private _activatedRoute: ActivatedRoute,
    private _environment: EnvironmentService,
  ) {}

  ngOnInit() {
    this.initProcessId();

    this._activatedRoute.url
      .pipe(takeUntil(this._onDestroy$), withLatestFrom(this._activatedRoute.queryParams, this._processId$))
      .subscribe(([_, queryParams, processId]) => {
        this.resetFilter(queryParams);
        this.removeBreadcrumbs(processId);
        this.addOrUpdateBreadcrumbs(processId, queryParams);
      });

    this._customerOrdersSearchStore.searchResultSubject
      .pipe(takeUntil(this._onDestroy$), withLatestFrom(this._processId$))
      .subscribe(async ([result, processId]) => {
        if (result.results.error) {
        } else {
          if (result.results.hits > 0) {
            const queryParams = this._customerOrdersSearchStore.filter.getQueryParams();
            if (result.results.hits === 1) {
              const orderItem = result.results.result[0];
              await this._navigationService
                .getCustomerOrdersDetailsPath({
                  processId,
                  processingStatus: orderItem?.processingStatus,
                  compartmentCode: orderItem?.compartmentCode
                    ? encodeURIComponent(orderItem.compartmentCode)
                    : undefined,
                  orderId: orderItem?.orderId ? orderItem.orderId : undefined,
                  extras: { queryParams },
                })
                .navigate();
            } else {
              await this._navigationService.getCustomerOrdersResultsPath(processId, { queryParams }).navigate();
            }
          } else {
            this._customerOrdersSearchStore.setMessage('keine Suchergebnisse');
          }
        }
      });
  }

  initProcessId() {
    this._processId$ = this._activatedRoute.parent.data.pipe(map((data) => Number(data.processId)));
  }

  ngOnDestroy(): void {
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  resetFilter(queryParams: Record<string, string>) {
    if (Object.keys(queryParams).length === 0) {
      this._customerOrdersSearchStore.resetFilter();
    }
  }

  async removeBreadcrumbs(processId: number) {
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(processId, ['checkout']);
  }

  async addOrUpdateBreadcrumbs(processId: number, queryParams: Record<string, string>) {
    await this._breadcrumb.addBreadcrumbIfNotExists({
      key: processId,
      name: 'Kundenbestellung',
      path: this._navigationService.getCustomerOrdersBasePath(processId).path,
      params: queryParams,
      tags: ['customer-order', 'main', 'filter'],
      section: 'customer',
    });
  }
}
