import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Store, Select } from '@ngxs/store';
import { Router } from '@angular/router';
import { ChangeCurrentRoute, RemoveSelectedItem } from '../../../../core/store/actions/process.actions';
import { DeliveryOption } from '../../../../core/models/delivery-option.model';
import { map, filter } from 'rxjs/operators';
import { deliveryFilter, cartToCartReviewArray, CartReviewItem } from '../../pages/cart-review/cart-review.component';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { Observable } from 'rxjs';
import { ProcessCart } from '../../../../core/models/process-cart.model';
import { isArrayMinLength } from '../../../../core/utils/app.utils';
import { AddBreadcrumb } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';
import { cartItem } from 'apps/sales/src/app/shared/animations/cart-item.animation';
import { DeleteProductFromCart } from 'apps/sales/src/app/core/store/actions/cart.actions';

@Component({
  selector: 'app-take-now-cart',
  templateUrl: './take-now-cart.component.html',
  styleUrls: ['./take-now-cart.component.scss'],
  animations: [cartItem],
})
export class TakeNowCartComponent implements OnInit {
  @Select(SharedSelectors.getCart) cartData$: Observable<ProcessCart>;
  @Output() editItem = new EventEmitter<boolean>();
  takeNow$: Observable<CartReviewItem[]>;
  blockingItem: number;
  lastDeletedItemIndex = -1;

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

  ngOnInit() {
    this.takeNow$ = this.cartData$.pipe(
      filter((c) => isArrayMinLength(c, 'cart', 0)),
      map((review) => review.cart),
      map(deliveryFilter(DeliveryOption.TAKE_NOW)),
      map((cart) => cartToCartReviewArray(cart))
    );
  }

  productDetails(item) {
    if (item) {
      this.store.dispatch(
        new AddBreadcrumb(
          {
            name: item.product.name ? item.product.name.substring(0, 12) + (item.product.name.length > 12 ? '...' : '') : '',
            path: '/product/details/' + item.id,
          },
          'product'
        )
      );
      this.store.dispatch(new RemoveSelectedItem());
      this.store.dispatch(new ChangeCurrentRoute(`product/details/${item.id}`));
      this.router.navigate([`product/details/${item.id}`]);
    }
  }

  blockModal(blockItemId?: number) {
    if (!blockItemId) {
      this.blockingItem = null;
      this.editItem.emit(false);
    } else {
      this.editItem.emit(true);
      this.blockingItem = blockItemId;
    }
  }

  getDeleteAnimation(index: number) {
    const animation = index >= this.lastDeletedItemIndex && this.lastDeletedItemIndex !== -1 ? 'delete' : '';
    return animation;
  }

  deleteItem(item: CartReviewItem, index: number) {
    this.lastDeletedItemIndex = index;
    if (item) {
      this.store.dispatch(new DeleteProductFromCart(item.cartId, item.cartEntryId));
    }
  }
}
