import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';
import { environment } from '../../../../environments/environment';
import { Cities } from '../../entities/cities';
import { Countries } from '../../entities/countries';
import { Courses } from '../../entities/courses';
import { Degrees } from '../../entities/degrees';
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-education-loan-apply',
  templateUrl: './education-loan-apply.component.html',
  styleUrls: ['./education-loan-apply.component.scss']
})
export class EducationLoanApplyComponent 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 contactForm: FormGroup;
  public basicDetailForm: FormGroup;
  public reCaptchaVerifier: any;
  public otp: any;
  public verify: any;
  public cities: Cities[] = new Array<Cities>();
  public serviceId: number = 0;
  public degrees: Degrees[] = new Array<Degrees>();
  public selectedDegree: Degrees = new Degrees();
  public courses: Courses[] = [];
  public selectedCourses: Courses[] = new Array<Courses>();
  public leads: Leads = new Leads();
  public countries: Countries[] = new Array<Countries>();
  public isAgreed: boolean = false;
  public agreedmsg: string = '';
  // public cities: any = [
  //   {
  //     name: "Bardoli"
  //   },
  //   {
  //     name: "Surat"
  //   },
  //   {
  //     name: "Kamrej"
  //   },
  //   {
  //     name: "Ahmedabad"
  //   }

  // ];
  public selectedCity: any = [] = [];
  constructor(
    private formBuilder: FormBuilder,
    private commonService: CommonService,
    private globalService: GlobalService,
    private toastrService: ToastrService,
    private leadService: LeadService,
    private meta: Meta,
    private spinnerService: NgxSpinnerService,
    private title: Title,
    private route: ActivatedRoute,
    private linkService: LinkService
  ) {
    this.linkService.createLinkForCanonicalURL();
    this.title.setTitle(this.route.snapshot.data['title']);
    this.meta.addTags([
      {
        name: 'description', content: `Get The Lowest Interest Rate Study Loan On Credit. Make Your Dream College Admission a Reality with Credit. Get instant loans from top NBFCs. Get Guidance From Experts. Free of Cost Consultation.`
      },
      {
        name: 'author', content: `Credit`
      },
      {
        name: 'og:title', property: "og:title", content: `compare & apply for Education loan`
      },
      {
        name: 'og:description', property: "og:description", content: `compare & apply for Education 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 Education loan`
      },
      {
        name: 'tweeter:title', content: `compare & apply for Education loan`
      },
      {
        name: 'tweeter:description', content: `compare & apply for Education 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)]],
      'customerFullName': [null, [Validators.required]],
      'pincode': [null, [Validators.required, Validators.minLength(6)]],
      'cityName': [null],
      'email': [null, [Validators.required, Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$")]],
      'studiedCountryId': [null, Validators.required],
      'degreeId': [null],
      'courseId': [null, [Validators.required]],
      'loanAmount': [null, [Validators.required]]
    })
    this.contactForm = formBuilder.group({
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
    });
  }

  async ngOnInit() {
    setTimeout(() => {
      this.isShow = false;
    }, 1000);
    // this.cities = await this.commonService.getCitites();
    // firebase.initializeApp(environment.firebase)
    // this.cities = await this.commonService.getCitites();
    // this.selectedCity = [...this.cities];
    this.serviceId = this.commonService.getServiceId("Education Loan");
    await this.getCourses();
    await this.getDegrees();
    await this.getCountries();
  }

  public async getDegrees() {
    try {
      let res = await this.globalService.getdegree();
      if (res && res.status == 200) {
        this.degrees = res.recordList;
        if (this.degrees && this.degrees.length > 0) {
          this.selectedDegree = this.degrees[0];
          if (this.courses && this.courses.length > 0) {
            this.courses.forEach((ele: any) => {
              if (ele.degreeId == this.selectedDegree.id) {
                this.selectedCourses.push(ele)
              }
            })
          }
        }
      }
    } catch (error: any) {
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public async getCourses() {
    try {
      let res = await this.globalService.getCourses();
      if (res && res.status == 200) {
        this.courses = res.recordList;
      }
    } catch (error: any) {
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public async getCountries() {
    try {
      let res = await this.globalService.getCountries();
      if (res && res.status == 200) {
        this.countries = res.recordList;
      }
    } catch (error: any) {
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public verifyOtp() {
    this.isOtpInput = true;
    this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
  }

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

  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) => {
      //alert(error.message);
      this.spinnerService.hide();
      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.isVerifyOtp = false;
    // this.isPersonalDetailForm = true;
    // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
    // 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.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
        this.isShow = true;
        this.getLeadsByContactNo();
        this.isShow = false;
        this.isPersonalDetailForm = true;
      }).catch((error) => {
        this.spinnerService.hide();
        this.commonService.showWarning();
        this.isVerifyOtp = true;
      });
  }

  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 getCourse(e: any) {
    this.selectedCourses = [];
    this.selectedDegree = this.degrees.find((c: { id: any; }) => c.id == e.value) as Degrees;
    if (this.courses && this.courses.length > 0) {
      this.courses.forEach((ele: any) => {
        if (ele.degreeId == e.value) {
          this.selectedCourses.push(ele)
        }
      })
    }
  }

  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.selectedDegree = this.degrees.find((c: any) => c.id == this.leads.degreeId) as Degrees;
          this.courses.forEach((ele: any) => {
            if (ele.id == this.leads.degreeId) {
              this.courses.push(ele);
            }
          })
          this.basicDetailForm.setValue(
            {
              "contactNo": this.leads.contactNo ? this.leads.contactNo : null,
              "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,
              "degreeId": this.leads.degreeId,
              "courseId": this.leads.courseId,
              "loanAmount": this.leads.loanAmount,
              "studiedCountryId": this.leads.studiedCountryId
            }
          )
        }
      }
    } 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.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.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 Education 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);
      }

    }
  }
}
