import { Subject } from 'rxjs';
import {
  Component,
  OnInit,
  Input,
  OnDestroy,
  Output,
  EventEmitter,
  ElementRef,
  Renderer2,
  AfterViewChecked,
  ViewChild,
} from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngxs/store';
import { AddSelectedProduct } from '../../../../core/store/actions/product.actions';
import { ChangeCurrentRoute } from '../../../../core/store/actions/process.actions';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { Product } from '../../../../core/models/product.model';
import { AddBreadcrumb } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.scss'],
})
export class ProductCardComponent implements OnInit, OnDestroy, AfterViewChecked {
  private _product: Product;
  @Input() index: number;

  @Input()
  get product() {
    return this._product;
  }

  set product(val) {
    if (val !== this.product) {
      this._product = val;
      if (this._product.publicationDate) {
        this.publicationDate = this.formatDate(this._product.publicationDate);
      } else {
        this.publicationDate = undefined;
      }
    }
  }

  @Output() authorFilter = new EventEmitter();
  @Output() saveProductPosition = new EventEmitter<number>();

  get price() {
    return this._product.price;
  }

  publicationDate: string;
  authors: string[];
  destroy$ = new Subject();

  @ViewChild('titleLine') titleLine: ElementRef;
  private clearAfterCheckedTimeout;

  constructor(public elementRef: ElementRef, private router: Router, private store: Store, private renderer: Renderer2) {}

  ngOnInit() {}

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

  ngAfterViewChecked(): void {
    clearTimeout(this.clearAfterCheckedTimeout);
    this.clearAfterCheckedTimeout = setTimeout(() => {
      if (!this.titleLine) {
        return;
      }
      const line = this.titleLine.nativeElement;
      const d = line.dataset.product;
      const p = `${this._product.id}`;
      if (d !== p) {
        this.renderer.setAttribute(line, 'data-product', `${this._product.id}`);
        this.renderer.removeClass(line, 'multi-line');
        if (line.offsetHeight > 40) {
          this.renderer.addClass(line, 'multi-line');
        }
      }
    }, 50);
  }

  productDetails(product: Product, element: HTMLElement, event: any) {
    if ((event.target.id as string).startsWith('author')) {
      return;
    }
    this.saveProductPosition.emit(this.index);
    // TODO: this is temporary solution for the incostency of product detail API
    const products = this.store.selectSnapshot(SharedSelectors.getSearchedProducts);
    if (products && products.itemsDTO) {
      const productDetailsData = products.itemsDTO[product.id];
      if (productDetailsData) {
        this.store.dispatch(new AddSelectedProduct(productDetailsData, this.index));
      }
    }

    if (product) {
      this.store.dispatch(
        new AddBreadcrumb(
          {
            name: product.title ? product.title.substring(0, 12) + (product.title.length > 12 ? '...' : '') : '',
            path: '/product/details/' + product.id,
          },
          'product'
        )
      );
      const currentRoute = 'product/details/' + product.id;
      this.store.dispatch(new ChangeCurrentRoute(currentRoute));
      this.router.navigate([currentRoute]);
    }
  }

  filterByAuthor(author: string) {
    if (!author) {
      return;
    }
    this.authorFilter.emit(author);
  }

  formatDate(date: Date): string {
    if (!!date) {
      try {
        const dateToFormat = new Date(date);
        const monthName = dateToFormat.toLocaleString('de', { month: 'long' });
        return `${monthName} ${dateToFormat.getFullYear()}`;
      } catch (error) {
        console.error(error);
        return '';
      }
    } else {
      return '';
    }
  }
}
