import { NgIf } from '@angular/common';
import { Component, NgZone, 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 { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { Countries, Country, VerifyLoginResponse } from '@interfaces/common';
import { LoginForm } 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-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, IonicSelectableComponent]
})
export class LoginPage implements OnInit {
  submitted = Boolean(false);
  countryCodes: Array<Country> = [];
  numLength = 10;
  loginForm: FormGroup<LoginForm>;
  showHideActive = Boolean(false);

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

  get frm() {
    return this.loginForm.controls;
  }

  ngOnInit() {
    this.loginForm = new FormGroup<LoginForm>({
      phoneCode: new FormControl(null, Validators.required),
      phoneNumber: new FormControl('', Validators.required),
    });
    if (this.stateManagementService.countryDetails.length > 0) {
      this.countryCodes = this.stateManagementService.countryDetails;
      this.setDefaultCountryCode();
    } else {
      this.fetchCountryCodes();
    }
    this.loginForm.controls.phoneNumber.setValidators([Validators.required, Validators.pattern('^[0-9]{10}$')]);
  }

  setDefaultCountryCode() {
    this.countryCodes.forEach((elem) => {
      if (elem.iso === 'IN') {
        this.loginForm.controls.phoneCode.setValue(elem);
      }
    });
  }

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

  async onSubmit(value: any) {
    this.submitted = true;
    if (this.loginForm.invalid) {
      this.loginForm.markAllAsTouched();
      return;
    } else {
      try {
        const codeVal = value.phoneCode.phone_code;
        const countryCode = codeVal.replace('(', '').replace(')', '');

        this.alert.showLoader();
        const res: VerifyLoginResponse = await this.httpRequestService.post(api.login, {
          email: value.phoneNumber,
          country_code: countryCode,
          via: 'OTP',
        });

        if (environment.production) {
          await this.firebaseService.signInWithPhoneNumber({
            phoneNumber: countryCode + value.phoneNumber
          });
        }

        const navOption = {
          state: {
            countryCode,
            phoneNumber: value.phoneNumber,
            redirectionFrom: 'login',
          },
        };
        this.navCtrl.navigateForward(Roots.auth + '/' + Roots.otp, navOption);
        this.alert.showToaster(res.message);
      } catch (error) {
        if (!error.error) { this.alert.showToasterError(error.message); }
      } finally {
        this.alert.hideLoader();
      }
    }
  }

  goToRegister() {
    this.zone.run(() => {
      this.navCtrl.navigateForward(Roots.auth + '/' + Roots.register);
    });
  }

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