import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Cities } from '../../entities/cities';
import { GlobalService } from '../../shared/services/common/global.service';

@Component({
  selector: 'app-refer-customer',
  templateUrl: './refer-customer.component.html',
  styleUrls: ['./refer-customer.component.scss']
})
export class ReferCustomerComponent implements OnInit {

  //public isShow: boolean = true;
  public customerDetailForm: FormGroup;
  public _title: string = '';

  public cities: Cities[] = new Array<Cities>();
  public selectedCity: any  = [];
  public token: string = '';

  public referLinkId: number = 0;
  public referenceUserId: number = 0;

  constructor(
    private formBuilder: FormBuilder,
    private meta: Meta,
    private title: Title,
    private route: ActivatedRoute,
    private globalService: GlobalService,
    private toastrService: ToastrService,
    private router: Router
  ) {

    this._title = `Refer Earn`;
    this.route.snapshot.data['title'] = this._title;
    this.title.setTitle(this.route.snapshot.data['title']);

    this.customerDetailForm = formBuilder.group({
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
      'fullName': [null, [Validators.required]],
      'panCardNo': [null, [Validators.required, Validators.pattern('[A-Z]{5}[0-9]{4}[A-Z]{1}')]],
      'pincode': [null, [Validators.required, Validators.minLength(6)]],
      'cityName': [null, [Validators.required]]
    })
  }

  async ngOnInit() {
    //setTimeout(() => {
    //  this.isShow = false;
    //}, 1000);

    await this.validateToken()
  }

  public async validateToken() {

    let sub = this.route.params.subscribe(async (params) => {
      this.token = params['token'];
    });

    try {
      //this.isShow = true;
      let res = await this.globalService.validateReferLink(this.token);
      if (res && res.recordList.length > 0) {
        this.referLinkId = res.recordList[0].id;
        this.referenceUserId = res.recordList[0].userId;
      } else {
        this.toastrService.error(res.message);
        setTimeout(() => {
          this.router.navigate(["/"])
        }, 500);
      }
      //setTimeout(() => {
      //  this.isShow = false;
      //}, 1000);
    } catch (error: any) {
      let err = '';
      if (error && error.error.message) {
        err = error.error.message
      }
      else if (error && error.message) {
        err = error.message
      }
      this.toastrService.error(error);
      setTimeout(() => {
        this.router.navigate(["/"])
      }, 500);
      //setTimeout(() => {
      //  this.isShow = false;
      //}, 1000);
    }
  }

  public async getCityByPincode(event: KeyboardEvent) {
    this.cities  = [];
    const value = (event.target as HTMLInputElement)!.value;;
    if (value && value.length == 6) {
      try {
        let res = await this.globalService.getCityByPincode(value);
        if (res && res.recordList.length > 0) {
          this.cities = res.recordList;
          this.selectedCity = [...this.cities]
        }
      } catch (error: any) {
        let err = '';
        if (error && error.error.message) {
          err = error.error.message
        }
        else if (error && error.message) {
          err = error.message
        }
        this.toastrService.error(err);
      }
    }
  }

  public async addCustomer() {
    try {
      debugger;
      if (this.customerDetailForm.valid) {
        let res = await this.globalService.insertReferCustomer(this.customerDetailForm.value.contactNo, this.customerDetailForm.value.fullName, this.customerDetailForm.value.panCardNo, this.customerDetailForm.value.pincode
          , this.customerDetailForm.value.cityName.id, this.customerDetailForm.value.cityName.name, this.customerDetailForm.value.cityName.districtName, this.customerDetailForm.value.cityName.stateName
          , this.referenceUserId, this.referLinkId);
        if (res && res.recordList.affectedRows >= 0) {
          this.toastrService.show("Rewarded Added to account. Please Login Via App", "Reward");
          setTimeout(() => {
            this.router.navigate(["/"])
          }, 1000);
        }
      } else {
        Object.keys(this.customerDetailForm.controls).forEach(field => {  //{2}
          const control = this.customerDetailForm.get(field);             //{3}
          if (control instanceof FormControl) {             //{4}
            control.markAsTouched({ onlySelf: true });
          }
        });
      }
    } catch (error: any) {
      let err = '';
      if (error && error.error.message) {
        err = error.error.message
      }
      else if (error && error.message) {
        err = error.message
      }
      this.toastrService.error(err);
    }
  }

}