import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  ViewChild,
} from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { SaleProduct, Stock } from 'src/app/models/sale-product.model';
import { MessageService } from 'src/app/services/messages.service';

@Component({
  selector: 'app-card-product',
  templateUrl: './card-product.component.html',
  styleUrls: ['./card-product.component.scss'],
})
export class CardProductComponent implements OnInit {
  @Input() product: SaleProduct;
  @Output() returnProduct = new EventEmitter();
  @ViewChild('addButton') addButton: ElementRef;
  stock$: Observable<Stock[]>;
  stockStore: Stock;
  /* Image card product */
  public imageWidth = '100%';
  public imageHeight = '350px';
  formQuantity: FormGroup;
  quantityOk = true;

  constructor(
    private fb: FormBuilder,
    private messageService: MessageService
  ) {}

  ngOnInit() {
    console.log(this.product);
    this.formQuantity = this.fb.group({
      quantity: new FormControl(this.product.mutiple.toFixed(2), []),
    });
    this.formQuantity.valueChanges.subscribe((_) => {
      const oldValue = this.formQuantity.get('quantity').value;
      this.quantityOk = Number.parseFloat(oldValue) <= this.product.stock;
    });
    /*  this.stock$ = this.productService.getStocks(this.product.idProduct);
      const data = localStorage.getItem('user');
      const user: UserAuth = JSON.parse(data);

      this.stock$.subscribe(d => {
         const stock = d.filter((s) => s.store === user.store);
         this.stockStore = stock[0];
      }); */
  }

  addQuantity(product: SaleProduct) {
    const oldValue = this.formQuantity.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.formQuantity.setValue({ quantity: newValue });
  }

  minusQuantity(product: SaleProduct) {
    const oldValue = this.formQuantity.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.formQuantity.setValue({ quantity: newValue });
  }

  addProductCart(product: any) {
    const baseValue = (this.product?.base ?? product?.base ?? '')
      .toString()
      .trim()
      .toUpperCase();
    if (baseValue === 'S') {
      this.messageService.showInformation(
        'Produto Tintométrico',
        'Esse produto só pode ser adicionado com coloração, usar o botão ver mais para adicionar cor'
      );
      return;
    }
    console.log(this.addButton.nativeElement.offsetLeft);
    console.log(this.addButton.nativeElement.offsetHeight);
    this.returnProduct.emit({
      ...this.product,
      quantity: this.formQuantity.get('quantity').value,
    });
  }

  existsPreCustomer() {
    return localStorage.getItem('preCustomer') != null;
  }
}
