import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/auth/auth.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment';
import { MatCardModule } from '@angular/material/card';
import { NgIf } from '@angular/common';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';

@Component({
  selector: 'diunabi-view-page',
  templateUrl: './login-view.component.html',
  styleUrls: ['./login-view.component.scss'],
  standalone: true,
  imports: [NgIf, MatCardModule, MatBottomSheetModule]
})

export class LoginViewComponent implements OnInit {
  constructor(
    private router$: Router,
    private auth$: AuthService,
    private ngZone$: NgZone,
    private notifications$: NotificationsService
  ) { }

  loading = false;

  ngOnInit(): void {
    setTimeout(() => {
      this.initGoogleLogin();
    }, 500);
  }

  initGoogleLogin() {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    google.accounts.id.initialize({
      client_id: environment.google.clientId,
      callback: this.handleCredentialResponse.bind(this),
      auto_select: true,
      cancel_on_tap_outside: true
    });
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore

    google.accounts.id.renderButton(
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      document.getElementById("google-button"),
      { theme: "outline", size: "large", width: "100%" }
    );
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    google.accounts.id.prompt();
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async handleCredentialResponse(response: any) {
    try {
      this.auth$.retrieveUserFromCredentials(response.credential);
      this.auth$.webCredentials = response.credential;
      this.auth$.sendAuthData();
      this.ngZone$.run(() => {
        this.loading = true;
      });
      await this.auth$.getAPIToken();
      this.ngZone$.run(() => {
        this.router$.navigate(['/app']);
      });
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (e: any) {
      console.error('handleCredentialResponse', e);
      this.ngZone$.run(() => {
        this.loading = false;
      });
      if (e.status === 401) {
        this.ngZone$.run(() => {
          this.notifications$.add({
            text: "User not exists in DiunaBI database.",
            btn: "OK",
            duration: 15000
          });
        });
      } else {
        this.ngZone$.run(() => {
          this.notifications$.add({
            text: "DiunaBI server not responded.",
            btn: "OK",
            duration: 15000
          });
        });
      }
    } finally {
      this.loading = false;
    }

  }
}

