import { Component, ElementRef, Inject, Renderer2 } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/shared/services/auth.service';
import { DOCUMENT } from '@angular/common';
import { TokenService } from 'src/app/shared/services/token.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page2.component.html',
  styleUrls: ['./login-page2.component.scss'],
})
export class LoginPageComponent {
  public showPassword = false;
  disabled = '';
  active: any;
  errorUser = false
  constructor(@Inject(DOCUMENT)
  private document: Document,
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private formBuilder: FormBuilder,
    private router: Router,
    private authservice: AuthService, private tokenService: TokenService,
    private employeeService: EmployeeService) {
    const bodyElement = this.renderer.selectRootElement('body', true);
    this.renderer.setAttribute(bodyElement, 'class', 'cover1 justify-center');

  }
  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      username: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required],
    });
    const authe: any = document.querySelector('.auth');
    authe.setAttribute('class', 'h-full');

    this.renderer.addClass(this.document.body, 'h-full');
    this.renderer.addClass(this.document.body, '!py-0');
    this.renderer.addClass(this.document.body, 'bg-white');
    this.renderer.addClass(this.document.body, 'dark:bg-bgdark');

    const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;
    html.removeAttribute('data-header-styles', 'light');

    //html.removeAttribute('data-nav-layout','vertical');
    html.classList.add('h-full', 'light');
    if (localStorage.getItem('synto-header-mode') == 'dark') {
      const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;
      html.classList.add('h-full', 'dark');
    }
  }

  // firebase
  email = 'spruko@admin.com';
  password = 'sprukoadmin';
  errorMessage = ''; // validation _error handle
  _error: { name: string; message: string } = { name: '', message: '' }; // for firbase _error handle

  clearErrorMessage() {
    this.errorMessage = '';
    this._error = { name: '', message: '' };
  }


  validateForm(email: string, password: string) {
    if (email.length === 0) {
      this.errorMessage = 'please enter email id';
      return false;
    }

    if (password.length === 0) {
      this.errorMessage = 'please enter password';
      return false;
    }

    if (password.length < 6) {
      this.errorMessage = 'password should be at least 6 char';
      return false;
    }

    this.errorMessage = '';
    return true;
  }

  //angular
  public loginForm!: FormGroup;
  public error: any = '';

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

  Submit() {
    // if (
    //   this.loginForm.controls['username'].value === 'spruko@admin.com' &&
    //   this.loginForm.controls['password'].value === 'sprukoadmin'
    // ) {
    //   this.router.navigate(['/self-evaluation']);
    // } else {
    //   this.error = 'Please check email and passowrd';
    // }
    if (this.loginForm.controls['username'].value &&
      this.loginForm.controls['password'].value) {
      sessionStorage.clear()
      this.authservice.loginWithUserPass(this.loginForm.controls['username'].value,
        this.loginForm.controls['password'].value).subscribe({
          next: response => {
            if (response) {
              this.errorUser = false
              this.tokenService.saveToken(response.accessToken);
              this.tokenService.saveRefreshToken(response.refreshToken);
              this.tokenService.saveUser(this.decodeJWT(response.accessToken))
              this.employeeService.getProfile().subscribe(result => {
                this.tokenService.saveUserData(result)
                this.router.navigate(['ess/my-skill-x-module']);
              })

            } else {
              this.errorUser = true
            }
          }, error: error => {
            this.error = 'Please check email and passowrd';
            this.errorUser = true
          }
        })
    } else {
      this.error = 'Please check email and passowrd';
      this.errorUser = true
    }
  }

  decodeJWT(token: string) {
    let base64Url = token.split('.')[1];
    let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
  }

  public togglePassword() {
    this.showPassword = !this.showPassword;
  }

  ngOnDestroy(): void {
    const bodyElement = this.renderer.selectRootElement('body', true);
    this.renderer.removeAttribute(bodyElement, 'class');
    this.renderer.removeClass(this.document.body, 'h-full');
    this.renderer.removeClass(this.document.body, '!py-0');
    this.renderer.removeClass(this.document.body, 'bg-white');
    this.renderer.removeClass(this.document.body, 'dark:bg-bgdark');
    if (localStorage.getItem('synto-header-mode') == 'dark') {
      const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;
      html.classList.remove('h-full', 'dark');
    }

    const authe: any = document.querySelector('.h-full');
    authe.removeAttribute('class', 'h-full');
  }
}
