import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { SearchComponentStoreService } from '@store/search-component-store';
import { UiFilter } from '@ui/filter';
import { NEVER, Observable, Subject } from 'rxjs';
import { filter, map, switchMap, takeUntil, withLatestFrom } from 'rxjs/operators';

@Component({
  selector: 'page-customer-search-main',
  templateUrl: 'search-main.component.html',
  styleUrls: ['search-main.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomerSearchMainComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject();

  customerCreateQueryParams?: Record<string, string>;

  processId$: Observable<number>;

  filter$ = this._store.filter$;

  fetching$ = this._store.fetching$;

  message$ = this._store.message$;

  constructor(
    public cdr: ChangeDetectorRef,
    private _breadcrumb: BreadcrumbService,
    private _activatedRoute: ActivatedRoute,
    private _store: SearchComponentStoreService
  ) {}

  ngOnInit() {
    this.processId$ = this._activatedRoute.parent.parent.data.pipe(map((d) => +d.processId));
    this._activatedRoute.url
      .pipe(takeUntil(this._onDestroy$), withLatestFrom(this.processId$))
      .subscribe(([_, processId]) => this.removeBreadcrumbs(processId));

    this.filter$
      .pipe(
        takeUntil(this._onDestroy$),
        switchMap((filter) => filter?.input?.find((i) => i.group === 'main')?.input.find((i) => i.key === 'qs')?.changes ?? NEVER),
        filter((change) => change.keys.includes('value'))
      )
      .subscribe((input) => this.updateCustomerCreateQueryParams(input?.target?.value));
  }

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

  async removeBreadcrumbs(processId: number) {
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(processId, ['customer', 'result']);
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(processId, ['customer', 'create']);
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(processId, ['customer', 'details']);
  }

  updateCustomerCreateQueryParams(value: string) {
    if (this.isValidEmail(value)) {
      this.customerCreateQueryParams = { email: value };
    } else {
      this.customerCreateQueryParams = { lastName: value };
    }
  }

  isValidEmail(email: string) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  }

  search(filter: UiFilter) {
    this._store.setFilter(filter);
    this._store.search({ clear: true });
  }
}
