import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { DialogCloseResult, DialogRef, DialogService, WindowCloseResult, WindowRef, WindowService } from '@progress/kendo-angular-dialog';
import { SaleProduct } from 'src/app/models/sale-product.model';
import { MessageService } from 'src/app/services/messages.service';
import { PreCustomerComponent } from '../pre-customer/pre-customer.component';
import { ProductModalComponent } from '../product-modal/product-modal.component';
import { TintometricoModalComponent } from '../tintometrico-modal/tintometrico-modal.component';
import { Router } from '@angular/router';

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.scss']
})
export class ProductCardComponent implements OnInit {
  @Input() product: SaleProduct;
  @Output() returnProduct = new EventEmitter();
  formQuantity: FormGroup;
  quantityOk = true;

  constructor(
    private fb: FormBuilder,
    private dialogService: DialogService,
    private windowService: WindowService,
    private messageService: MessageService,
    private router: Router) { }

  ngOnInit(): void {
    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;
    });
    console.log(this.product);
  }

  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;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    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;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.formQuantity.setValue({ quantity: newValue });
  }

  addProductCart(product: any) {
    this.returnProduct.emit({ ...this.product, quantity: this.formQuantity.get('quantity').value });
  }

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

  showModalProduct(product: any) {
    const customer = localStorage.getItem('customer');
    const preCustomer = localStorage.getItem('preCustomer');

    // if ( customer ===  null && preCustomer === null ){{
    //   const windowRef: WindowRef = this.windowService.open({
    //     title: 'Pré-cadastro de cliente',
    //     content: PreCustomerComponent,
    //     width: 350,
    //     height: 400,
    //   });
    //   windowRef.result.subscribe((result) => {
    //     if (result instanceof WindowCloseResult) {
    //       console.log('WindowCloseResult', result);
    //     }
    //   });
    //   windowRef.content.instance.submitForm.subscribe((formData) => {
    //     // handle form data
    //     console.log(formData);
    //     localStorage.setItem('preCustomer', JSON.stringify(formData));
    //     windowRef.close();
    //   });
    // }}

    if ( product.base === 'S') {
      let resultProduct: any;
      const dialogRef: DialogRef = this.dialogService.open({
        content: TintometricoModalComponent,
      });

      const productInfo = dialogRef.content.instance as TintometricoModalComponent;
      productInfo.product = product;
      dialogRef.result.subscribe((result) => {
        if (result instanceof DialogCloseResult) {
          console.log('WindowCloseResult', result);
        } else {
          console.log('action', result);
          resultProduct = JSON.stringify(result);
          console.log(resultProduct);
          this.messageService.showMessage(JSON.parse(resultProduct).message);
        }
      });

    } else {
      this.router.navigate(['product-sale'], {state: { product: product }  })
      // let resultProduct: any;
      // const dialogRef: DialogRef = this.dialogService.open({
      //   content: ProductModalComponent,
      // });

      // const productInfo = dialogRef.content.instance as ProductModalComponent;
      // productInfo.product = product;
      // dialogRef.result.subscribe((result) => {
      //   if (result instanceof DialogCloseResult) {
      //     console.log('WindowCloseResult', result);
      //   } else {
      //     console.log('action', result);
      //     resultProduct = JSON.stringify(result);
      //     console.log(resultProduct);
      //     this.messageService.showMessage(JSON.parse(resultProduct).message);
      //   }
      // });
    }

  }

}
