import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { isDevMode } from '@angular/core';
import {
  Auth,
  signInWithPopup,
  GoogleAuthProvider,
  connectAuthEmulator,
} from '@angular/fire/auth';

import { environment } from 'src/environments/environment.development';

import { AuthService } from 'src/app/core/services/auth/auth.service';
import { StoreService } from 'src/app/core/services/store/store.service';
import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';

import {
  LoaderDispatchers,
  SignupDispatchers,
} from 'src/app/core/stores/index.dispatchers';
import { SignupStore } from 'src/app/core/interfaces/store/signup.store';

@Component({
  selector: 'app-google-button',
  templateUrl: './google-button.component.html',
  styleUrls: ['./google-button.component.scss'],
})
export class GoogleButtonComponent {
  constructor(
    private auth: Auth,
    private googleProvider: GoogleAuthProvider,
    private apiFitService: ApiFitService,
    private authService: AuthService,
    private storeService: StoreService,
    private router: Router,
    private loaderDispatchers: LoaderDispatchers,
    private signupDispatchers: SignupDispatchers,
  ) {
    if (isDevMode()) {
      //connectAuthEmulator(this.auth, environment.firebaseEmulators.auth.url);
    }
  }

  async loginWithGoogle() {
    try {
      this.loaderDispatchers.showLoader();

      const { user } = await signInWithPopup(this.auth, this.googleProvider);

      const googleToken = await user.getIdToken();

      this.apiFitService
        .loginWithGoogle({
          googleToken,
        })
        .subscribe({
          next: (res) => {
            this.authService.setAuthorizationToken(res.data.accessToken);
            this.storeService.setStore();

            this.loaderDispatchers.hideLoader();

            this.router.navigate(['/app']);
          },
          error: () => {
            this.signupDispatchers.setSignup({
              fullName: user.displayName,
              email: user.email,
              googleToken,
            } as SignupStore);
            this.loaderDispatchers.hideLoader();

            this.router.navigate(['/app/auth/signup']);
          },
        });
    } catch (err) {
      this.loaderDispatchers.hideLoader();
    }
  }
}
