import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Cities } from '../../entities/cities';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import { environment } from '../../../../environments/environment';
import { CommonService } from '../../shared/services/common/common.service';
import { ToastrService } from 'ngx-toastr';
import { LeadService } from '../../shared/services/loanService/lead.service';
import { GlobalService } from '../../shared/services/common/global.service';
import { Leads } from '../../entities/leads';
import { Meta, Title } from '@angular/platform-browser';
import Swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute } from '@angular/router';
import { LinkService } from '../../shared/services/link.service';

@Component({
  selector: 'app-car-loan-apply',
  templateUrl: './car-loan-apply.component.html',
  styleUrls: ['./car-loan-apply.component.scss']
})
export class CarLoanApplyComponent implements OnInit {
  public isVerifyOtp: boolean = true;
  public isShow: boolean = true;
  public isDetailForm: boolean = false;
  public isPersonalDetailForm: boolean = false;
  public mobileNumber: number = 0;
  public isOtpInput: boolean = false;
  public selectedCourse: string = '';
  public otp: any;
  public verify: any;
  public cities: Cities[] = new Array<Cities>();
  public leads = new Leads();
  // public cities: any = [
  //   {
  //     name: "Bardoli"
  //   },
  //   {
  //     name: "Surat"
  //   },
  //   {
  //     name: "Kamrej"
  //   },
  //   {
  //     name: "Ahmedabad"
  //   }

  // ];
  public reCaptchaVerifier: any;
  public contactForm: FormGroup;
  public basicDetailForm: FormGroup;
  public selectedCity: any = [];
  public serviceId: number = 0;

  constructor(
    private formBuilder: FormBuilder,
    private commonService: CommonService,
    private toastrService: ToastrService,
    private leadService: LeadService,
    private globalService: GlobalService,
    private meta: Meta,
    private title: Title,
    private route: ActivatedRoute,
    private spinnerService: NgxSpinnerService,
    private linkService: LinkService
  ) {
    this.linkService.createLinkForCanonicalURL();
    this.title.setTitle(this.route.snapshot.data['title']);
    this.meta.addTags([
      {
        name: 'description', content: `Easy to compare and apply for any type of loan at Credit - compare with different banks's interest rate and select the plan with the lowest emi cost , Apply for credit card by just 1 single click, Credit is the right place to sign up as DSA that best fits your needs and helps you make the most of your purchases.`
      },
      {
        name: 'author', content: `Credit`
      },
      {
        name: 'og:title', property: "og:title", content: `compare & apply for Car Loan`
      },
      {
        name: 'og:description', property: "og:description", content: `compare & apply for Car Loan - credit.nsserver.in`
      },
      {
        name: 'og:site_name', property: "og:site_name", content: `Credit`
      },
      {
        name: 'og:type', property: "og:type", content: `Website`
      },
      {
        name: 'og:image', property: "og:image", content: `../../../assets/img/logo/logo.webp`
      },
      {
        name: 'tweeter:card', content: `compare & apply for Car Loan`
      },
      {
        name: 'tweeter:title', content: `compare & apply for Car Loan`
      },
      {
        name: 'tweeter:description', content: `compare & apply for car loan with low cost EMI - credit.nsserver.in`
      },
      {
        name: 'tweeter:site', content: `Credit`
      },
      {
        name: 'tweeter:image', content: `../../../assets/img/logo/logo.webp`
      }
    ]);

    this.basicDetailForm = formBuilder.group({
      'loanAmount': [null, [Validators.required]],
      'customerFullName': [null, [Validators.required]],
      'pincode': [null, [Validators.required, Validators.minLength(6)]],
      'cityName': [null, [Validators.required]],
      'email': [null, [Validators.required, Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$")]],
      'aadhaarCardNo': [null, [Validators.required, Validators.pattern('^[2-9]{1}[0-9]{3}[0-9]{4}[0-9]{4}$')]],
      'panCardNo': [null, [Validators.required, Validators.pattern('[A-Z]{5}[0-9]{4}[A-Z]{1}')]],
    })
    this.contactForm = formBuilder.group({
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
    });
  }

  async ngOnInit() {
    // this.cities = await this.commonService.getCitites();
    // this.selectedCity = [...this.cities];
    this.serviceId = this.commonService.getServiceId("Car Loan");
    // firebase.initializeApp(environment.firebase)
  }
  public verifyOtp() {
    this.isOtpInput = true;
  }

  public detailForm(isNext: boolean) {
    if (isNext) {
      this.isDetailForm = true;
      this.isPersonalDetailForm = false;
    }
    else {
      this.isDetailForm = false;
      this.isPersonalDetailForm = true;
    }
  }

  //#region getOtp
  public getOtp() {
    // this.isVerifyOtp = false;
    // this.isPersonalDetailForm = true;
    // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
    this.isOtpInput = true;
    this.spinnerService.show();
    this.reCaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', { size: 'invisible' })
    firebase.auth().signInWithPhoneNumber('+91' + this.contactForm.value.contactNo, this.reCaptchaVerifier).then((confirmationResult) => {
      if (confirmationResult && confirmationResult.verificationId) {
        this.verify = JSON.parse(JSON.stringify(confirmationResult.verificationId));
        this.isOtpInput = true;
        this.spinnerService.hide();
      }
    }).catch((error) => {
      this.spinnerService.hide();
      //alert(error.message);
      this.toastrService.error(error.message, "Firebase");
      setTimeout(() => {
        window.location.reload();
      }, 5000);
    });
  }

  public onOtpChange(otpCode: any) {
    this.otp = otpCode;
  }

  public handleClick() {
    this.isVerifyOtp = false;
    this.spinnerService.show();
    // this.isPersonalDetailForm = true;
    // this.getLeadsByContactNo();
    var credential = firebase.auth.PhoneAuthProvider.credential(this.verify, this.otp);
    firebase.auth().signInWithCredential(credential)
      .then((response) => {
        this.isVerifyOtp = false;
        this.spinnerService.hide();
        this.isShow = true;
        this.getLeadsByContactNo();
        this.isShow = false;
        this.isPersonalDetailForm = true;
      }).catch((error) => {
        this.spinnerService.hide();
        this.commonService.showWarning();
      });
  }

  //#endregion

  public onKey(event: KeyboardEvent) {
    const value = (event.target as HTMLInputElement)!.value;
    this.selectedCity = this.search(value);
  }

  public search(value: string) {
    let filter = this.cities.filter(item =>
      item.name.toLowerCase().includes(value.toLowerCase())
    );
    return [...filter];
  }

  public async getLeadsByContactNo() {
    try {
      let res = await this.globalService.getLeadsByContactNo(this.contactForm.value.contactNo, this.serviceId);
      if (res && res.status == 200) {
        if (res.recordList && res.recordList.length > 0) {
          this.leads = res.recordList[0];
          if (res.recordList[0].pincode) {
            let data = await this.getCityByPincode(res.recordList[0].pincode);
          }
          this.basicDetailForm.setValue(
            {
              "loanAmount": this.leads.loanAmount,
              "customerFullName": this.leads.customerFullName,
              "pincode": this.leads.pincode ? this.leads.pincode : null,
              "cityName": this.cities.find((c: any) => c.id == this.leads.cityId),
              "email": this.leads.email,
              "panCardNo": this.leads.panCardNo,
              "aadhaarCardNo": this.leads.aadhaarCardNo
            }
          )
          // let id = this.employmentTypes.find((c:any) => c.name == "Self Employee")?.id
        }
      }
    } catch (error: any) {
      this.isShow = false;
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public async generateLead() {
    try {
      this.isShow = true;
      if (this.leads.id) {

        let id = this.leads.id
        this.leads = this.basicDetailForm.value;
        this.leads.contactNo = this.contactForm.value.contactNo
        this.leads.serviceId = this.serviceId;
        this.leads.cityId = this.basicDetailForm.value.cityName.id;
        this.leads.id = id;
        this.leads.countryCode = "+91";
        let res = await this.leadService.updateLeads(this.leads);
        if (res && res.status == 200) {
          this.sucessReponse();
        }
      }
      else {

        this.leads = this.basicDetailForm.value;
        this.leads.contactNo = this.contactForm.value.contactNo
        this.leads.serviceId = this.serviceId;
        this.leads.cityId = this.basicDetailForm.value.cityName.id;
        this.leads.countryCode = "+91";
        let res = await this.leadService.insertLeads(this.leads);
        if (res && res.status == 200) {
          if (res.recordList && res.recordList.length > 0) {
            this.leads.id = res.recordList[0].id
            this.sucessReponse();
          }
        }
      }
      this.isShow = false;
    } catch (error: any) {
      this.isShow = false;
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public sucessReponse() {
    //this.commonService.showSuccess();
    Swal.fire({
      icon: 'success',
      text: 'Your Car loan inquiry is submitted successfully.',
      confirmButtonColor: '#0162e8'
    })
    this.isPersonalDetailForm = false;
    this.isVerifyOtp = true;
    this.isOtpInput = false;
    this.leads = new Leads();
    this.contactForm.reset();
  }

  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(error);
      }

    }
  }
}
