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 { 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, FormConstants, HiddenValues, supportedLanguages } from '../../utils/enums';
import { environment } from '../../../environments/environment';
import { AuthenticationService } from '../../services/authenticate.service';
import { UserCredentials } from '../authenticate';
import { NgSelectModule } from '@ng-select/ng-select';

@Component({
  selector: 'app-login',
  imports: [TranslateModule, ReactiveFormsModule, CommonModule, PasswordHideShowComponent, NgSelectModule],
  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 = '';
  languageOptions = [
  { label: 'English', value: supportedLanguages.ENGLISH },
  { label: 'Arabic', value: supportedLanguages.ARABIC }
];

  ucred: UserCredentials = new UserCredentials();
  @ViewChild(PasswordHideShowComponent) passwordHideShow?: PasswordHideShowComponent;

  constructor(
    private authService: AuthenticationService,
    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') || supportedLanguages.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.LTR;
      this.storageService.setItem('direction', this.direction);
    }
    if (typeof document !== 'undefined') {
    document.documentElement.setAttribute('dir', this.direction);
    document.documentElement.setAttribute('lang', 
      this.direction === directions.LTR ? 'ar' : 'en');
  }
  }

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

  login() {
     if (this.loginForm.valid) {
      this.ucred.password = this.loginForm.get(FormConstants.PASSWORD)?.value;
      this.ucred.userId = this.loginForm.get(FormConstants.USER_ID)?.value?.toLowerCase().trim();
      this.authService.authenticate(this.ucred).subscribe( (res: any) => {
        const user = res?.user;
        this.storageService.setItem('user', JSON.stringify(res));

        if (res?.requiresPasswordChange || user?.firstLogin) {
          console.log('First time login - redirecting to first-login-change-password');
          this.router.navigate(['/first-login-change-password']); 
        } else {
          console.log('Regular login - redirecting to dashboard');
          this.router.navigate(['/home/dashboard']); 
        }
    
      });
    }
  
  }
  

  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';
  }

}
