import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Cities } from '../../entities/cities';
import { CommonService } from '../../shared/services/common/common.service';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import { environment } from '../../../../environments/environment';
import { Leads } from '../../entities/leads';
import { LeadService } from '../../shared/services/loanService/lead.service';
import { GlobalService } from '../../shared/services/common/global.service';
import { ToastrService } from 'ngx-toastr';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { isPlatformBrowser } from '@angular/common';
import Swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
import { LinkService } from '../../shared/services/link.service';
declare let $: any;
@Component({
  selector: 'app-msme-loan',
  templateUrl: './msme-loan.component.html',
  styleUrls: ['./msme-loan.component.scss']
})
export class MsmeLoanComponent implements OnInit {
  public isVerifyOtp: boolean = true;
  //public isShow: boolean = true;
  public isPersonalDetailForm: boolean = false;
  public isOtpInput: boolean = false;
  public selectedType: string = '';
  public selectedCity: Cities[] = new Array<Cities>();
  public interest_rate: number = 0;
  public payment: string = "0.00";
  public months: number = 0;
  public interest: string = "0.00";
  public amountPayable: string = "0.00";
  public displayAmount: string = "0.00";
  public amount: number = 0;
  public contactForm: FormGroup;
  public basicDetailForm: FormGroup;
  public reCaptchaVerifier: any;
  public otp: any;
  public verify: any;
  public cities: Cities[] = new Array<Cities>();
  public leads = new Leads();
  public serviceId: number = 0;
  public city: string = "";

  constructor(
    private formBuilder: FormBuilder,
    private commonService: CommonService,
    private leadService: LeadService,
    private globalService: GlobalService,
    private toastrService: ToastrService,
    private meta: Meta,
    private title: Title,
    private route: ActivatedRoute,
    @Inject(PLATFORM_ID) public platformId: object,
    private spinnerService: NgxSpinnerService,
    private linkService: LinkService
  ) {
    this.linkService.createLinkForCanonicalURL();
    let sub = this.route.params.subscribe(async (params) => {
      this.city = params['city'] ? params['city'] : '';
      if (this.city) {
        if (isPlatformBrowser(this.platformId))
          sessionStorage.setItem("selectedCity", this.city);
      }
    });
    let cityList;
    if (isPlatformBrowser(this.platformId))
      cityList = sessionStorage.getItem("cityList");
    let isCityAvailable = false;
    if (cityList) {
      let cityArray = JSON.parse(cityList) as string[];
      isCityAvailable = cityArray.findIndex(c => c == this.city.toLowerCase()) > -1;
    }

    this.title.setTitle(this.route.snapshot.data['title']);

    if (isCityAvailable) {
      this.meta.addTags([
        {
          name: 'description', content: this.city + ` 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 msme Loan`
        },
        {
          name: 'og:description', property: "og:description", content: `compare & apply for msme 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 msme loan`
        },
        {
          name: 'tweeter:title', content: `compare & apply for msme loan`
        },
        {
          name: 'tweeter:description', content: `compare & apply for msme loan with low cost EMI - credit.nsserver.in`
        },
        {
          name: 'tweeter:site', content: `Credit`
        },
        {
          name: 'tweeter:image', content: `../../../assets/img/logo/logo.webp`
        }
      ]);
    } else {
      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 msme Loan`
        },
        {
          name: 'og:description', property: "og:description", content: `compare & apply for msme 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 msme loan`
        },
        {
          name: 'tweeter:title', content: `compare & apply for msme loan`
        },
        {
          name: 'tweeter:description', content: `compare & apply for msme 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({
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
      'loanAmount': [null, [Validators.required]],
      'customerFullName': [null, [Validators.required]],
      'cityName': [null, [Validators.required]],
      'email': [null, [Validators.required, Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$")]],
    })
    this.contactForm = formBuilder.group({
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
    });
  }

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

    // this.cities = await this.commonService.getCitites();
    // this.selectedCity = [...this.cities];
    this.serviceId = this.commonService.getServiceId("Msme Loan");
  }
  public verifyOtp() {
    this.isOtpInput = true;
    this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
    console.log('Your form data : ', this.contactForm.value);
  }
  public calculateLoan() {
    if (this.amount && this.interest_rate && this.months) {
      let rate = this.interest_rate / (12 * 100);
      let rate1 = (Math.pow(1 + rate, this.months))
      let payment = this.amount * rate * (rate1 / (rate1 - 1));
      this.payment = payment.toFixed(2);
      this.amountPayable = (parseFloat(this.payment) * this.months).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.interest = (parseFloat(this.payment) * this.months - this.amount).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.displayAmount = this.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
  }

  //#region getOtp

  public getOtp() {
    this.isOtpInput = true;
    this.spinnerService.show();
    // this.isVerifyOtp = false;
    // this.isPersonalDetailForm = true;
    // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
    // this.isOtpInput = true;
    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.getLeadsByContactNo();
    // this.isVerifyOtp = false;
    // this.isPersonalDetailForm = true;
    // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
    this.basicDetailForm.controls['mobile'].setValue(this.contactForm.value.mobile);
    var credential = firebase.auth.PhoneAuthProvider.credential(this.verify, this.otp);
    firebase.auth().signInWithCredential(credential)
      .then((response) => {
        this.isVerifyOtp = false;
        this.spinnerService.hide();
        this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
        //this.isShow = true;
        this.getLeadsByContactNo();
        //this.isShow = false;
        this.isPersonalDetailForm = true;
      }).catch((error) => {
        this.spinnerService.hide();
        //alert(error.message);
        this.toastrService.error(error.message, "Firebase");
      });
  }

  //#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];
          this.basicDetailForm.setValue(
            {
              "contactNo": this.leads.contactNo,
              "loanAmount": this.leads.loanAmount,
              "customerFullName": this.leads.customerFullName,
              "cityName": this.cities.find((c: any) => c.id == this.leads.cityId),
              "email": this.leads.email,
            }
          )
          // 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;
        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;
        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 = true;
    } 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 MSME loan inquiry is submitted successfully.',
      confirmButtonColor: '#0162e8'
    })
    this.isPersonalDetailForm = false;
    this.isVerifyOtp = true;
    this.isOtpInput = false;
    this.leads = new Leads();
    this.contactForm.reset();
  }

  public applyNow() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    })
  }

}