import { 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 { Roots } from '@enums/root.enum';
import { Countries, Country, Dharma } from '@interfaces/common';
import { SignupForm } 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';
import { UtilityService } from '@services/utility.service';
import { format, parseISO } from 'date-fns';
@Component({
  selector: 'app-signup',
  templateUrl: './signup.page.html',
  styleUrls: ['./signup.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf, IonicSelectableComponent, NgFor]
})
export class SignupPage implements OnInit {
  countryDetails: Array<Country> = [];
  dharmaDetails: Array<Dharma> = [];
  maxDate: any;
  numLength = 10;
  dateValue = '';
  signupForm: FormGroup;
  showHideActive = Boolean(false);
  showConfirmHideActive = Boolean(false);
  confirmationFlag = false;

  constructor(
    private navCtrl: NavController,
    private alert: AlertService,
    private httpRequestService: HttpRequestService,
    private stateManagementService: StateManagementService,
    private firebaseService: FirebaseService,
    private utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.signupForm = new FormGroup<SignupForm>({
      name: new FormControl('', Validators.required),
      countryCode: new FormControl('', Validators.required),
      mobileNumber: new FormControl('', Validators.required),
      dharma: new FormControl('', Validators.required)
    });
    this.maxDate = this.formatDate(new Date((new Date()).setFullYear((new Date()).getFullYear() - 14)).toISOString());
    if (this.stateManagementService.countryDetails.length > 0) {
      this.countryDetails = this.stateManagementService.countryDetails;
      this.setDefaultCountryCode();
    } else {
      this.getCountryDetails();
    }
    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    this.signupForm.controls.mobileNumber.setValidators([Validators.required, Validators.pattern('^[0-9]{10}$')]);
    this.signupForm.controls.mobileNumber.updateValueAndValidity();
  }

  setDefaultCountryCode() {
    this.countryDetails.forEach((elem) => {
      if (elem.iso === 'IN') {
        this.signupForm.controls.countryCode.setValue(elem);
      }
    });
  }

  backToLogin() {
    this.navCtrl.navigateRoot(Roots.auth + '/' + Roots.login);
  }

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

  formatDate(value: string) {
    return format(parseISO(value), 'yyyy-MM-dd');
  }

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

  getDharmaDetails() {
    this.httpRequestService.get(api.dharmaDetails).then((res: any) => {
      this.dharmaDetails = res.data;
      this.stateManagementService.dharmaDetails = res.data;
    });
  }

  async onSignUp(form) {
    if (!this.signupForm.valid || !this.confirmationFlag) {
      this.signupForm.markAllAsTouched();
      return;
    }

    const codeVal = form.value.countryCode.phone_code;
    const countryCode = codeVal.replace('(', '').replace(')', '');

    const params = {
      name: form.value.name,
      email: form.value.mobileNumber,
      dharma: form.value.dharma,
      country_code: countryCode,
      verified: 0,
    };
    try {
      this.alert.showSpinner();
      await this.httpRequestService.post(api.signUp, params);
      await this.firebaseService.signInWithPhoneNumber({ phoneNumber: countryCode + form.value.mobileNumber });
      const navOption = {
        state: {
          countryCode,
          phoneNumber: form.value.mobileNumber,
          redirectionFrom: 'register',
          signupData: params
        },
      };
      this.navCtrl.navigateForward(Roots.auth + '/' + Roots.otp, navOption);
    } catch (error) {
      if (!error.error) { this.alert.showToasterError(error.message); }
    } finally {
      this.alert.hideLoader();
    }
  }

  async goToPolicy(type: number) {
    this.utilityService.openBrowser(type === 1 ? constants.privacyPolicy : constants.termsAndConditions);
  }
}
