import { Component, OnInit, Input, AfterViewInit, ViewChild, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Store, Select } from '@ngxs/store';
import { Observable, Subject } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { SearchInputComponent } from '@libs/ui';
import { Process } from '../../../../core/models/process.model';
import { Breadcrumb } from '../../../../core/models/breadcrumb.model';
import { AddBreadcrumb } from '../../../../core/store/actions/breadcrumb.actions';
import { AddProcess, ChangeCurrentRoute, AddCustomerSearch } from '../../../../core/store/actions/process.actions';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { CustomerSearchResult } from '../../../../core/models/customer-search-result.model';
import { AppState } from 'apps/sales/src/app/core/store/state/app.state';
import { CustomerService } from 'apps/sales/src/app/core/services/customer.service';
import { CustomerSearchResponse } from 'apps/sales/src/app/core/models/customer-search-response.model';
import { CUSTOMER_SCROLL_INDEX } from 'apps/sales/src/app/core/utils/app.constants';
import { ClearCachedCustomers, SetCachedCustomers } from 'apps/sales/src/app/core/store/actions/customer.actions';
import { CustomerFeatures } from 'apps/sales/src/app/core/models/customer-features.model';
import { CustomerSearchEmptyModalComponent } from '../customer-search-empty-modal/customer-search-empty-modal.component';

@Component({
  selector: 'app-search-customer-card',
  templateUrl: './customer-search-card.component.html',
  styleUrls: ['./customer-search-card.component.scss'],
})
export class CustomerSearchCardComponent implements OnInit, AfterViewInit, OnDestroy {
  @Select(SharedSelectors.getSearchedCustomers) customers$: Observable<CustomerSearchResult>;

  destroy$ = new Subject();
  processes: Process[];
  searchError = '';

  @Input() searchParams = '';
  @ViewChild('searchInput')
  searchInput: SearchInputComponent;
  @ViewChild('searchEmptyModal')
  searchEmptyModal: CustomerSearchEmptyModalComponent;

  constructor(private store: Store, private router: Router, private customerService: CustomerService) {}

  ngOnInit() {
    this.store.dispatch(new ClearCachedCustomers());
  }

  ngAfterViewInit() {
    this.searchInput.focus();
  }

  search(searchParams) {
    this.searchParams = searchParams;
    if (!this.searchParams) {
      return;
    }

    this.searchParams = this.searchParams.trim();

    if (this.searchParams.length < 2) {
      return;
    }

    this.customerService
      .searchCustomer(this.searchParams, false, 0, 10, false)
      .pipe(take(1), takeUntil(this.destroy$))
      .subscribe((r: CustomerSearchResponse) => {
        if (r.customers.length > 0) {
          const filteredCustomer = r.customers.filter((data) => {
            if (isNullOrUndefined(data) || !data.features) {
              return true;
            }
            const customerFeatures = new CustomerFeatures(data.features);
            if (customerFeatures.guest) {
              return false;
            }
            return true;
          });
          const response = {
            ...r,
            customers: filteredCustomer,
            hits: r.hits,
          };

          this.store.dispatch(
            new AddBreadcrumb(
              {
                name:
                  (searchParams.length > 12 ? searchParams.substring(0, 12) + '...' : searchParams) +
                  ` (${
                    !isNullOrUndefined(response)
                      ? !isNullOrUndefined(response.hits)
                        ? response.hits
                        : response.customers
                        ? response.customers.length
                        : 0
                      : 0
                  } Ergebnisse)`,
                path: '/customer/results',
              },
              'customer'
            )
          );
          this.store.dispatch(
            new AddCustomerSearch({
              query: searchParams,
              skip: 0,
              take: 5,
              firstLoad: true,
            })
          );
          sessionStorage.removeItem(CUSTOMER_SCROLL_INDEX);
          this.store.dispatch(new SetCachedCustomers(response));
          this.store.dispatch(new ChangeCurrentRoute('customer/results'));
          this.router.navigate(['customer/results']);
        } else {
          this.searchInput.stopLoading();
          this.searchError = 'Ergibt keine Suchergebnisse';

          if (!!r.message) {
            this.searchEmptyModal.openDialog(r.message);
          }
        }
      });
  }

  createProcess() {
    const newProcess = <Process>{
      id: 1,
      name: 'Vorgang 1',
      currentRoute: '/product/search',
    };

    this.store.dispatch(new AddProcess(newProcess));
    this.store.dispatch(
      new AddBreadcrumb(
        <Breadcrumb>{
          name: 'Artikelsuche',
          path: '/product/search',
        },
        'customer'
      )
    );
  }

  createTab() {
    if (!this.searchError) {
      const processes = this.store.selectSnapshot(AppState.getProcessCount);
      if (processes === 0) {
        this.createProcess();
      }
    }
  }

  ngOnDestroy() {
    this.destroy$.next();
  }
}
