import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Store } from '@ngrx/store';
import { Observable, of, Subscription } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { SaleProduct, Stock } from 'src/app/models/sale-product.model';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { AddItemAction } from '../../store/actions/shopping.action';
import { SaleState } from '../../store/models/sale-state.model';
import { ShoppingItem } from '../../store/models/shopping-item';

@Component({
  selector: 'app-shopping-item-modal',
  templateUrl: './shopping-item-modal.component.html',
  styleUrls: ['./shopping-item-modal.component.scss']
})

export class ShoppingItemModalComponent implements OnInit, OnDestroy, OnChanges {

  @Input() item: ShoppingItem;
  @Input() product: SaleProduct;

  form: FormGroup;
  quantityOk = true;
  loading$: Observable<boolean>;
  error$: Observable<Error>;
  stocks: Stock[];
  error: Error = null;
  subscriptionProduct: Subscription;
  subscriptionItem: Subscription;
  public dataDelivery = [{ type: 'RI', description: 'Retira imediata' },
  { type: 'EN', description: 'Entrega' },
  { type: 'RP', description: 'Retira posterior' },
  { type: 'EF', description: 'Entrega futura' },
  ];

  constructor(
    private fb: FormBuilder,
    private shoppingService: ShoppingService,
    private productService: ProductService,
    private store: Store<SaleState>,
    private readonly authService: AuthService,
  ) {
  }

  ngOnInit(): void {
    console.log('Modal item: ' + JSON.stringify(this.item));
    this.loading$ = this.store.select(store => store.shopping.loading);
    this.error$ = this.store.select(store => store.shopping.error);
    this.error$.subscribe((error) => {
      this.error = error;
    });
    this.form = this.fb.group({
      quantity: new FormControl('', []),
      salePrice: new FormControl('', []),
      store: new FormControl('', []),
      deliveryType: new FormControl('', []),
    });
    this.form.valueChanges.subscribe((_) => {
      const oldValue = this.form.get('quantity').value;
      this.quantityOk = Number.parseFloat(oldValue) <= this.product.stock;
    });


    /*if (this.item) {
      this.subscriptionItem = this.productService.getSaleProduct(this.authService.getStore(),
      this.item == null ? 0 : this.item.idProduct)
        .pipe(
          map((product) => {
            this.product = product;
          })
          //   switchMap(() =>
          //     this.productService.getStocks(this.item.idProduct = null ? 0 : this.item.idProduct)
          //   ),
          //   map((stock) => {
          //     this.stocks = stock;
          //   }),
          //   catchError((err) => of(err))
        )
        .subscribe(() => {
          console.log(this.item);
        }
        );
    } */
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('mostrando em ngOnChanges');
  }
  ngOnDestroy(): void {
    if (this.subscriptionProduct) {
      this.subscriptionProduct.unsubscribe();
    }
    if (this.subscriptionItem) {
      this.subscriptionItem.unsubscribe();
    }
  }

  addQuantity(product: SaleProduct) {
    const oldValue = this.form.get('quantity').value;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    let newValue = (Number.parseFloat(oldValue) + addQuantity);
    if (newValue > product.stock) {
      newValue = oldValue;
    }
    this.form.patchValue({ quantity: newValue });
  }

  minusQuantity(product: SaleProduct) {
    const oldValue = this.form.get('quantity').value;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    let newValue = (Number.parseFloat(oldValue) - addQuantity);
    if (newValue < 0 || newValue < product.mutiple) {
      newValue = product.mutiple;
    }
    this.form.patchValue({ quantity: newValue });
  }


  public onConfirmation() {
    console.log('botao acionado');
    // this.dialog.close();
  }

  async addProductCard(product: any) {
    try {
      const idCart = this.shoppingService.getCart();
      const quantity = this.form.get('quantity').value;
      const quantitySale = Math.ceil(quantity / product.mutiple) * product.mutiple;
      this.error = null;
      this.store.dispatch(new AddItemAction({
        id: null, idCart, invoiceStore: this.authService.getStore(),
        idProduct: product.idProduct, description: product.title, image: product.urlImage, productType: product.productType,
        quantity: quantitySale, price: product.salePrice, deliveryType: (product.productType === 'A') ? 'RI' : 'EN',
        stockStore: (product.productType === 'A') ? this.authService.getStore() : '6', seller: this.authService.getSeller(),
        discount: 0, discountValue: 0, ean: product.ean, promotion: ( product.offPercent > 0 ) ?  product.salePrice : 0,
        listPrice: product.listPrice, userDiscount: null, mutiple: product.mutiple, percentUpQuantity: 0, upQuantity: 0,
        auxDescription: null, smallDescription: product.smallDescription, brand: product.brand, base: product.base,
        line: product.line, color: product.color, can: product.can, letter: product.letter,
      }));
      this.loading$.subscribe((inProcess) => {
        console.log(inProcess);
        if (this.error) {
          //  this.dialog.close({ success: false, message: this.error.message });
          console.log('Erro ocorrido: ' + JSON.stringify(this.error));
        }
        if (!inProcess && this.error == null) {
          //   this.dialog.close({ success: true, message: 'Produto incluído com sucesso!' });
        }
      });
    } catch (e) {
      console.log(e);
    }
  }

}
