import { Component, Inject, inject, PLATFORM_ID, ViewChild } from '@angular/core';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';

import { CONSTANTS } from '../../utils/app.constants';
import { PasswordHideShowComponent } from '../../shared/components/password-hide-show/password-hide-show.component';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { MiscService } from '../../shared/services/misc.service';
import { User } from '../../models/user';
import { CommonModule, isPlatformBrowser } from '@angular/common';
import { StorageService } from '../../shared/services/storage.service';
import { directions, supportedLanguages } from '../../utils/enums';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-login',
  imports: [TranslateModule, ReactiveFormsModule, CommonModule, PasswordHideShowComponent],
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss'
})
export class LoginComponent {
  versionNumber: string = '';
  buildDate: string = '';
  buildNumber: string = '';
  loginForm!: FormGroup;
  currentLanguage = new FormControl();
  passwordType: string = 'password';
  direction: string = '';
  supportedLanguages = supportedLanguages;
  @ViewChild(PasswordHideShowComponent) passwordHideShow?: PasswordHideShowComponent;

  constructor(
    private authService: AuthService,
    private translateService: TranslateService,
    private router: Router,
    private miscService: MiscService,
    private storageService: StorageService,
    @Inject(PLATFORM_ID) private platformId: object
  ) {
    this.initializeLanguage();
  }

  ngOnInit() {
    this.initializeLoginForm();
  }

  setVersionNumberAndBuildDate(){
    this.translateService.get('versionAndBuildNumber', {
      versionNumber: environment.versionNumber,
      buildNumber: environment.buildNumber
    }).subscribe((res: string) => {
      this.versionNumber = res;
    });

    this.translateService.get('versionBuildDate', {
      date: environment.buildDate
    }).subscribe((res: string) => {
      this.buildDate = res;
    })
  }

  initializeLanguage(): void {
    if (isPlatformBrowser(this.platformId)) {
      const savedLanguage = this.storageService.getItem('language') || 'English';
      this.storageService.setItem('language', savedLanguage);
      this.currentLanguage.setValue(savedLanguage)
      this.translateService.setDefaultLang(savedLanguage);
      this.translateService.use(savedLanguage).subscribe(() => {
        this.setVersionNumberAndBuildDate();
      });
      this.setDirection();
    }
  }

  setDirection() {
    let selectedLang = this.currentLanguage.value;
    if (selectedLang === supportedLanguages.ENGLISH) {
      this.direction = directions.LTR;
      this.storageService.setItem('direction', this.direction);
    }
    else {
      this.direction = directions.RTL;
      this.storageService.setItem('direction', this.direction);
    }
  }

  initializeLoginForm() {
    this.loginForm = new FormGroup({
      USER_ID: new FormControl('', [Validators.required, Validators.pattern('^[a-z0-9]*$')]),
      PASSWORD: new FormControl('', [Validators.required])
    })
  }

  async login() {
    let User: User = {
      Username: this.loginForm.get("USER_ID")?.value,
      Password: this.loginForm.get("PASSWORD")?.value
    }
    let response = await this.authService.login(User);
    if ((await response["errorMessage"] == undefined)) {
      if (await response) {
        if (!this.authService.firstLogin) {
          this.router.navigate(['home/dashboard']);
          this.miscService.handleSuccess(this.translateService.instant('loginSuccess'));
        }
        else {
          this.router.navigate(['/changepassword']);
          this.miscService.handleSuccess(this.translateService.instant('passwordChangeRequired'));
        }
      }
    }
    else {
      this.miscService.handleError(await response["errorMessage"])
    }
  }

  onLangChange() {
    const selectedLang = this.currentLanguage.value;
    this.translateService.setDefaultLang(selectedLang);
    this.translateService.use(selectedLang).subscribe(() => {
      this.setVersionNumberAndBuildDate();
    });
    this.storageService.setItem('language', selectedLang);
    this.setDirection();
    // document.documentElement.setAttribute('dir', this.direction); 
  }

  togglePasswordType() {
    this.passwordType = this.passwordHideShow?.showPassword ? 'password' : 'text';
  }

}
