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

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

  // //public isShow: boolean = true;
  // public interest_rate: number
  // 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 selectedTab: string = "Overview"
  // public faqs = [
  //   {
  //     que: "My car loan repayments can be calculated using a calculator, but where can I get one?",
  //     ans: "On a different website, you may find our car EMI calculator. On the car loan webpage, click the 'EMI Calculator' link to use the tool.",
  //     isCollapsed: false
  //   },
  //   {
  //     que: "Is it feasible to use the car calculator to reduce my monthly payments?",
  //     ans: "Yes! Using this tool, you may alter the figures for various loan factors until you find an appropriate monthly payment amount.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "Is it safe to use an EMI calculator to figure out how much a car would cost each month?",
  //     ans: "Yes! Using this tool, you may alter the figures for various loan factors until you find an appropriate monthly payment amount.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "There aren't any charges involved with making use of the EMI estimator. Is the EMI calculator free to use?",
  //     ans: "No! By visiting our website, you can access this free resource whenever and however often you like.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "In order to access the amortization schedule, what is the process for doing so?",
  //     ans: "After you've calculated your EMI, click 'Check Repayment Schedule' to see your repayment schedule. You can interact with an interactive table that contains all of the loan payment data.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "How to Reduce the Monthly Pre- Owned Car Loan Installment Payment ? ",
  //     ans: "It's critical to keep your monthly payments low when borrowing wisely. Reasonable monthly payments have two advantages: they allow you to pay your debts on time and prevent you from going into default. Follow these steps to get the rewards: <ul class='bfaq'> <li>Put down a greater deposit</li> <li>Borrow money at a lower interest rate</li> <li>Make payments to the lender during the loan's term</li> <li>If you wish to transfer your balance, you must first decide if you want to do so </li> <li>Attempt to persuade your lender to reduce the interest rate you're paying </li>  <li>You should hunt for a job that will last you a long time. </li></ul>",
  //     isCollapsed: true
  //   },
  // ];
  // public city: string = "";
  // public _title: string = '';

  public leads = new Leads();
  public basicDetailForm: FormGroup;
  public selectedCity: any;
  public cities: Cities[] = [];
  public serviceId: number = 0;
  public city: string = "";
  public _title: string = '';
  public payment: string = "0.00";
  public interest: string = "0.00";
  public amountPayable: string = "0.00";
  public displayAmount: string = "0.00";
  public test: any
  public emiCalculatorForm: FormGroup;
  public documentMasters: DocumentMasters[] = new Array<DocumentMasters>();
  public customFieldForm!: FormGroup;

  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,
    @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;
    }

    //if (isCityAvailable) {
    this._title = `Apply for low interest car loans in India and experience quick loan disbursal.`;
    this.route.snapshot.data['title'] = this._title;
    this.title.setTitle(this.route.snapshot.data['title']);

    this.meta.updateTag({
      name: 'description', content: `Cheapest car loan available in ` + this.city + ` for salaried and self-employed professionals. Avail low interest car loans in ` + this.city + ` and instant digital approval. Apply now!`
    });
    this.meta.updateTag({
      name: 'author', content: `Credit`
    });
    this.meta.updateTag({
      name: 'og:locale', property: "og:locale", content: `en_US`
    });
    this.meta.updateTag({
      name: 'og:title', property: "og:title", content: `Apply for low interest car loans in India and experience quick loan disbursal.`
    });
    this.meta.updateTag({
      name: 'og:description', property: "og:description", content: `Cheapest car loan available in ` + this.city + ` for salaried and self-employed professionals. Avail low interest car loans in ` + this.city + ` and instant digital approval. Apply now!`
    });
    this.meta.updateTag({
      name: 'og:url', property: "og:url", content: `https://credit.nsserver.in`
    });
    this.meta.updateTag({
      name: 'og:site_name', property: "og:site_name", content: `Credit`
    });
    this.meta.updateTag({
      name: 'og:type', property: "og:type", content: `Website`
    });
    this.meta.updateTag({
      name: 'og:image', property: "og:image", content: `https://credit.nsserver.in/assets/img/logo/logo.webp`
    });
    this.meta.updateTag({
      'http-equiv': "X-UA-Compatible", content: "IE=edge"
    });
    this.meta.updateTag({
      name: 'copyright', content: `Copyright 2022, Credit`
    });
    this.meta.updateTag({
      name: 'robots', content: `index, follow`
    });
    this.meta.updateTag({
      name: 'Googlebot', content: `Index, Follow`
    });
    this.meta.updateTag({
      name: 'rating', content: `Safe For Kids`
    });
    this.meta.updateTag({
      name: 'tweeter:card', content: `compare & apply for business loan`
    });
    this.meta.updateTag({
      name: 'tweeter:title', content: `compare & apply for business loan`
    });
    this.meta.updateTag({
      name: 'tweeter:description', content: `Cheapest car loan available in ` + this.city + ` for salaried and self-employed professionals. Avail low interest car loans in ` + this.city + ` and instant digital approval. Apply now!`
    });
    this.meta.updateTag({
      name: 'tweeter:site', content: `Credit`
    });
    this.meta.updateTag({
      name: 'tweeter:image', content: `https://credit.nsserver.in/assets/img/logo/logo.webp`
    });

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

  async ngOnInit() {
    this.serviceId = this.commonService.getServiceId("Car Loan");
    console.log(this.serviceId);
    await this.getDocumentMaster();
    if (this.documentMasters && this.documentMasters.length > 0) {
      this.customFieldForm = this.formBuilder.group({})
      for (let index = 0; index < this.documentMasters.length; index++) {
        if (this.documentMasters[index].allowDocumentField) {
          this.customFieldForm.addControl(this.documentMasters[index].documentFieldName, this.formBuilder.control(''));
        }
      }
    }
  }

  public async getDocumentMaster() {
    try {
      let res = await this.globalService.getDocumentMaster();
      if (res && res.status == 200) {
        this.documentMasters = res.recordList;
      }
    } catch (error: any) {
      this.toastrService.error(error)
    }
  }

  public async detailForm() {
    if (this.basicDetailForm.valid) {
      try {

        this.spinnerService.show();
        this.leads = this.basicDetailForm.value;
        this.leads.serviceId = this.serviceId;
        this.leads.cityId = this.basicDetailForm.value.cityName.id;
        this.leads.countryCode = "+91";
        if (this.documentMasters && this.documentMasters.length > 0) {
          for (let index = 0; index < this.documentMasters.length; index++) {
            if (this.documentMasters[index].allowDocumentField)
              this.documentMasters[index].documentData = this.customFieldForm.get(this.documentMasters[index].documentFieldName)?.value
          }
          this.leads.customfields = this.documentMasters
        }
        let res = await this.leadService.insertLeads(this.leads);
        if (res && res.status == 200) {
          this.sucessReponse();
        }

        this.spinnerService.hide();
      } catch (error: any) {
        this.spinnerService.hide();
        let err = error;
        if (error && error.error && error.error.message) {
          err = error.error.message
        }
        this.toastrService.error(err, "Error");
      }
    }
    else {
      Object.keys(this.basicDetailForm.controls).forEach(key => {
        this.basicDetailForm.controls[key].markAsTouched();
      });
    }
  }

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

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

  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]
          if (this.selectedCity && this.selectedCity.length > 0)
            this.basicDetailForm.get('cityName')?.setValue(this.selectedCity[0])
        }
      } 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);
      }
    }
  }

  // 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, ",");
  //   }
  // }
  // public setStep(n: any, initial?: string) {
  //   if (initial) {
  //     this.faqs[0].isCollapsed = false;
  //   }
  //   else {
  //     if (this.faqs[n].isCollapsed == false) {
  //       this.faqs[n].isCollapsed = true;
  //     }
  //     else {
  //       for (let index = 0; index < this.faqs.length; index++) {
  //         if (this.faqs[index].isCollapsed == false) {
  //           this.faqs[index].isCollapsed = true;
  //         }
  //       }
  //       this.faqs[n].isCollapsed = false;
  //     }
  //   }
  // }
  public calculateLoan() {

    if (this.emiCalculatorForm.value.amount && this.emiCalculatorForm.value.interest_rate && this.emiCalculatorForm.value.months) {
      let rate = this.emiCalculatorForm.value.interest_rate / (12 * 100);
      let rate1 = (Math.pow(1 + rate, this.emiCalculatorForm.value.months))
      let payment = this.emiCalculatorForm.value.amount * rate * (rate1 / (rate1 - 1));
      this.payment = payment.toFixed(2);
      this.amountPayable = (parseFloat(this.payment) * this.emiCalculatorForm.value.months).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.interest = (parseFloat(this.payment) * this.emiCalculatorForm.value.months - this.emiCalculatorForm.value.amount).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.displayAmount = this.emiCalculatorForm.value.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    }
  }
  public keyPressAlphanumeric(event: { keyCode: number; preventDefault: () => void; }) {
    var inp = String.fromCharCode(event.keyCode);
    if (/[a-zA-Z0-9 ]/.test(inp)) {
      // only alphabet a-z A-Z
      return true;
    } else {
      event.preventDefault();
      return false;
    }
  }
}