import { NgClass, NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, Countries, Country, Privacy, ProfileData } from '@interfaces/common';
import { ContactForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { FirebaseService } from '@services/firebase.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';

@Component({
  selector: 'app-shravak-edit-contact-info',
  templateUrl: './shravak-edit-contact-info.page.html',
  styleUrls: ['./shravak-edit-contact-info.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgFor, IonicSelectableComponent, NgClass]
})
export class ShravakEditContactInfoPage implements OnInit {
  privacyList: Privacy[] = constants.privacy;
  contactForm: FormGroup<ContactForm>;
  userProfileData: ProfileData;
  numLength = 10;
  countryDetails: Array<Country> = [];
  countryCode: string;
  phoneNumber: string;
  timer: string;
  interval: any;
  resendEnable = false;
  verifyOtpBtn = false;
  codeSentFlag = false;
  serializedForm: string;
  constructor(
    private stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private firebaseService: FirebaseService
  ) { }

  async ngOnInit() {
    this.userProfileData = await this.stateManagementService.storage.get(GJainStorage.profileData);
    this.contactForm = new FormGroup<ContactForm>({
      country_code: new FormControl(null, Validators.required),
      mobile: new FormControl(this.userProfileData.mobile, Validators.required),
      mobile_privacy: new FormControl(this.userProfileData.mobile_privacy, Validators.required),
      email: new FormControl(this.userProfileData.email, [Validators.email]),
      email_privacy: new FormControl(this.userProfileData.email_privacy,),
      otp: new FormControl(''),
    });
    if (this.stateManagementService.countryDetails.length > 0) {
      this.countryDetails = this.stateManagementService.countryDetails;
      this.setDefaultCountryCodeAndValidate();
    } else {
      this.getCountryDetails();
    }
    this.serializedForm = this.getSerializedForm(this.contactForm);
  }

  setDefaultCountryCodeAndValidate() {
    if (this.countryDetails) {
      this.countryDetails.forEach((elem) => {
        const countryCode = elem.phone_code.replace('(', '').replace(')', '');
        if (countryCode === this.userProfileData.country_code) {
          this.contactForm.controls.country_code.setValue(elem);
          this.numLength = Number(elem.num_length);
          this.contactForm.controls.mobile.setValidators([Validators.pattern(`^[0-9]{${this.numLength}}$`)]);
          this.contactForm.controls.mobile.updateValueAndValidity();
        }
      });
    }
  }

  getSerializedForm(form) {
    const formObj = form.getRawValue();
    return JSON.stringify(formObj);
  }

  initTimer() {
    let seconds = 60;
    this.interval = setInterval(() => {
      if (seconds > 0) {
        seconds--;
        this.timer = `00:${(seconds > 10 ? seconds : '0' + seconds)}`;
        this.resendEnable = true;
      } else {
        this.timer = null;
        this.resendEnable = false;
        clearInterval(this.interval);
      }
    }, 1000);
  }

  onSubmit(form) {
    if (!this.contactForm.valid) {
      this.contactForm.markAllAsTouched();
      return;
    }
    if (form.value.country_code.phone_code) {
      const codeVal = form.value.country_code.phone_code;
      const countryCode = codeVal.replace('(', '').replace(')', '');
      form.value.country_code = countryCode;
    }
    if (this.serializedForm === this.getSerializedForm(form)) {
      this.alert.showToaster('No changes to save');
      return;
    }
    this.httpRequestService.post(api.updateShravakProfile, form.value).then((res: CommonResponse) => {
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
      this.alert.showToaster(res.message);
    });
  }

  async logout() {
    const deviceUUID = await this.stateManagementService.storage.get(GJainStorage.deviceUUID);
    const params = {
      device_id: deviceUUID,
    };
    this.httpRequestService.get(api.logout, deviceUUID ? params : '').then((res: any) => {
      if (res.status === 200) {
        this.stateManagementService.token = '';
        this.stateManagementService.storage.remove(GJainStorage.loginType);
        this.stateManagementService.storage.remove(GJainStorage.profileData);
        this.stateManagementService.storage.remove(GJainStorage.userData).then(() => {
          this.navCtrl.navigateRoot(Roots.auth + '/' + Roots.login);
        });
      }
      this.alert.showToaster(res.message);
      this.alert.hideLoader();
    }).catch(() => {
      this.alert.hideLoader();
    });
  }

  codeChange(event) {
    this.numLength = event.value.num_length;
    this.contactForm.controls.mobile.setValidators([Validators.pattern(`^[0-9]{${this.numLength}}$`)]);
    this.contactForm.controls.mobile.updateValueAndValidity();
  }

  getCountryDetails() {
    this.httpRequestService.get(api.countryCodes).then((res: Countries) => {
      this.countryDetails = res.countries;
      this.stateManagementService.countryDetails = res.countries;
      this.setDefaultCountryCodeAndValidate();
    });
  }

  async phoneNumberVerification(phoneCode: any, phoneNumber: string) {
    const codeVal = phoneCode.phone_code;
    const countryCode = codeVal.replace('(', '').replace(')', '');
    const params = {
      country_code: countryCode,
      mobile: phoneNumber,
    };
    try {
      this.alert.showLoader();
      const response: any = await this.httpRequestService.post(api.userExistNumber, params);
      if (response) {
        await this.firebaseService.signInWithPhoneNumber({
          phoneNumber: countryCode + phoneNumber
        });
        this.countryCode = countryCode;
        this.phoneNumber = phoneNumber;
        this.codeSentFlag = true;
        this.initTimer();
        this.contactForm.controls.otp.setValidators([Validators.required]);
        this.contactForm.controls.otp.updateValueAndValidity();
        this.alert.showToaster(response.message);
      }
    } catch (error) {
      if (!error.error) { this.alert.showToasterError(error.message); }
    } finally {
      this.alert.hideLoader();
    }
  }

  async verifyOtp(form) {
    if (
      this.contactForm.controls.mobile.value !== this.userProfileData.mobile &&
      this.contactForm.controls.country_code.value.phone_code !== this.userProfileData.country_code
    ) {
      if (!this.contactForm.valid) {
        this.contactForm.markAllAsTouched();
        return;
      }
      if (form.value.country_code.phone_code) {
        const codeVal = form.value.country_code.phone_code;
        const countryCode = codeVal.replace('(', '').replace(')', '');
        form.value.country_code = countryCode;
      }
      this.alert.showLoader();
      this.firebaseService.confirmVerificationCode(form.value.otp).then(() => {
        this.httpRequestService.post(api.updateShravakProfile, form.value).then((res: CommonResponse) => {
          this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
          this.alert.showToaster(res.message);
        });
      }).catch(e => {
        this.alert.showToasterError(e.message);
      }).finally(() => {
        this.alert.hideLoader();
      });
    } else {
      this.onSubmit(form);
    }
  }

  resendOtp() {
    this.phoneNumberVerification(this.contactForm.controls.country_code.value, this.contactForm.controls.mobile.value);
  }

  changeNumber(event) {
    if (event.detail.value !== this.userProfileData.mobile) {
      this.verifyOtpBtn = true;
      this.contactForm.controls.otp.setValidators([Validators.required]);
      this.contactForm.controls.otp.updateValueAndValidity();
    } else {
      this.verifyOtpBtn = false;
      this.contactForm.controls.otp.clearValidators();
      this.contactForm.controls.otp.updateValueAndValidity();
    }
  }

}
