import { Component, OnInit, AfterViewInit, NgZone } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';

import { AuthenticationService } from '../../../core/services/auth.service';
import { AuthfakeauthenticationService } from '../../../core/services/authfake.service';

import { ActivatedRoute, Router } from '@angular/router';
import { first } from 'rxjs/operators';

import { environment } from '../../../../environments/environment';
import { SupportLoginMethod,UserData } from './authList.model';
import { AuthDataList } from './authListData';
import { TranslateService } from '@ngx-translate/core';
import { UserService } from 'src/app/pages/userlist/user.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { StorageService } from 'src/app/shared/service/storage.service';
import { CookieService } from 'ngx-cookie-service';
import { ToastService } from 'src/app/toast/toast-service';
export const MOCK_USERS = [
  {
    username: 'admin',
    password: 'admin',
    roles: ['Admin'],
    permissions: [
      'Read Device Data',
      'Read Role Data',
      'Read User Data',
      'Read Tenant Data',
      'Read Customer Data'
    ]
  },
  {
    username: 'librarian',
    password: 'lib',
    roles: ['Librarian'],
    permissions: [
      'Read Device Data',
      'Read Customer Data'
    ]
  },
  {
    username: 'student',
    password: 'stu',
    roles: ['Student'],
    permissions: []
  }
];


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})


/**
 * Login component
 */
export class LoginComponent implements OnInit, AfterViewInit {

  loginForm: UntypedFormGroup;
  submitted = false;
  error = '';
  returnUrl: string;
  nextClicked = false;
  passwordVisible = false;

  passwordValid: boolean = false;
  showPasswordTooltip: boolean = false;
  passwordLengthValid: boolean = false;
  passwordUpperCaseValid: boolean = false;
  passwordLowerCaseValid: boolean = false;
  passwordNumberValid: boolean = false;
  passwordSpecialCharValid: boolean = false;
  supportLoginMethods: SupportLoginMethod[] = [];
  // authDatalist:UserData;

  // set the currenr year
  year: number = new Date().getFullYear();

  defaultIconClass: string = 'uil uil-user';
  isLoggedIn: boolean;
  user: any;
  acctForm: any;
  isNative: boolean;
  ssoLgns: any;
  socialLgns: any;
  loginError: boolean;
  roles: any;

  // tslint:disable-next-line: max-line-length
  constructor(private formBuilder: UntypedFormBuilder, private route: ActivatedRoute, private router: Router, private authenticationService: AuthenticationService,
    private authFackservice: AuthfakeauthenticationService,public baseService: BaseService,      
    // public userService: UserService,
    public translate: TranslateService,
    private storrage:StorageService,private cookieService: CookieService,private ngZone: NgZone ,private toastService: ToastService
    //private mssgService:MessageService,
   ) { 

    //translate.addLangs(['en', 'fr']);
    //translate.setDefaultLang('en');
   // translate.setDefaultLang('en');

    // the lang to use, if the lang isn't available, it will use the current loader to get them
   //translate.use('en');

   }

   
  

  ngOnInit() {
    document.body.setAttribute('class', 'authentication-bg');

   this.loginForm = this.formBuilder.group({
  username: ['', Validators.required],
  password: ['', Validators.required],
});

    // reset login status
    // this.authenticationService.logout();
    // get return url from route parameters or default to '/'
    // tslint:disable-next-line: no-string-literal
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    // var userData: UserData = AuthDataList; // Fetch userData from your service
    // if (userData && userData.support_login_methods) {
    //   this.supportLoginMethods = userData.support_login_methods;
    // }
  }

  ngAfterViewInit() {
  }

  ngOnDestroy() { 
    document.body.classList.remove('authentication-bg')
  }

  // convenience getter for easy access to form fields
  get f() { return this.loginForm.controls; }

  get emailControl() {
    return this.loginForm.get('email'); // Access the email control
  }

  get userControl(){
    return this.loginForm.get('username'); 
  }
  get passwordControl(){
    return this.loginForm.get('password'); 
  }

  /**
   * Form submit
   */
  // onSubmit() {
  //   this.submitted = true;

  //   // stop here if form is invalid
  //   if (this.loginForm.invalid) {
  //     return;
  //   } else {
  //     // if (environment.defaultauth === 'firebase') {
  //     //   this.authenticationService.login(this.f.email.value, this.f.password.value).then((res: any) => {
  //     //     document.body.removeAttribute('class');
  //     //     this.router.navigate(['/']);
  //     //   })
  //     //     .catch(error => {
  //     //       this.error = error ? error : '';
  //     //     });
  //     // } else {
  //     //   console.log("Inside else");
  //     //   this.authFackservice.login(this.f.email.value, this.f.password.value)
  //     //     .pipe(first())
  //     //     .subscribe(
  //     //       data => {
  //     //         this.router.navigate(['/']);
  //     //       },
  //     //       error => {
  //     //         this.error = error ? error : '';
  //     //       });
  //     // }

  //   const formData = new URLSearchParams();
  //   formData.append('Username', this.loginForm.get('username').value);
  //   formData.append('password', this.loginForm.get('password').value);
  //   formData.append('loginType', 'DB');

  //   this.baseService.postData('auth/authenticate', formData).subscribe(
  //     (data: any) => {
  //       if (data) {
  //       console.log(data);
  //       const parsedData = JSON.parse(data.data);
  //       const accessToken = parsedData.accessToken;

  //       // Save the token in the cookie and local storage
  //       this.cookieService.set('token', accessToken);
  //       localStorage.setItem('currentUser', JSON.stringify(parsedData));
  //       this.getUserPermissions(this.loginForm.get('username').value)

  //       console.log(this.router);
        
  //       this.router.navigate(['/']);

  //       console.log(this.router);
  //       this.toastService.show('login successfully!', { classname: 'bg-success text-light', delay: 3000 });

  //       }
  //     },
  //     (err) => {
  //       console.log(err);
  //       this.toastService.show('login unsuccessfully please check username and password!', { classname: 'bg-error text-light', delay: 3000 });
  //     }
  //   );


  //   }
  // }
  

onSubmit() {
  this.submitted = true;
  this.error = '';

  if (this.loginForm.invalid) return;

  const username = this.loginForm.get('username')?.value;
  const password = this.loginForm.get('password')?.value;

  const payload = { username, password };
   const formData = new URLSearchParams();
    formData.append('Username', username);
    formData.append('password', password);


   this.baseService.postData('auth/authenticate', formData)
    .subscribe({
      next: (res:any) => {

        console.log('Login response', res);

        if (res?.status !== 'Success') {
          this.error = res.message || 'Login failed';
          return;
        }

        /* ✅ Store token only */
        this.cookieService.set('token', res.token);
        localStorage.setItem('username', res.username);

        // ⭐ KEEP RBAC DISABLED FOR NOW
        // localStorage.setItem('role', user.roles[0]);
        this.storrage.setItem('permissions', JSON.stringify(res.permissions));
          // this.storrage.setItem("permissions",data.user.permissions);

          this.storrage.setItem("role",res.roles[0]);

          this.storrage.setItem("user",res.userID);
          // this.storrage.setItem("username",res.username);

console.log(this.router);
        
        this.router.navigate(['/']);
      },
      error: (err) => {
        console.error(err);
        this.error = 'Invalid username or password';
      }
    });
}



  onNext() {
    // Check if the email field is invalid
    if (this.loginForm.get('email').invalid) {
      this.submitted = true;
      return;
    }
  
    const formData = new URLSearchParams();
    formData.append('email', this.loginForm.get('email').value);
  
    this.baseService.postData('user/exists', formData).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          this.nextClicked = true;
          this.checkIfUsrExist(data)
          // this.toastService.show('login email checked successfully!', { classname: 'bg-success text-light', delay: 3000 });
        }
      },
      (err) => {
        this.submitted = true;
        this.toastService.show('login email incorrect!', { classname: 'bg-error text-light', delay: 3000 });

      }
    );
  }
  togglePasswordVisibility() {
    this.passwordVisible = !this.passwordVisible;
  }

  checkPassword() {
    const password = this.loginForm.get('password').value;
    this.passwordLengthValid = password.length >= 8;
    this.passwordUpperCaseValid = /[A-Z]/.test(password);
    this.passwordLowerCaseValid = /[a-z]/.test(password);
    this.passwordNumberValid = /[0-9]/.test(password);
    this.passwordSpecialCharValid = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    this.passwordValid = this.passwordLengthValid && this.passwordUpperCaseValid && this.passwordLowerCaseValid && this.passwordNumberValid && this.passwordSpecialCharValid;
  }
  hasSocialMethods(): boolean {
    return this.supportLoginMethods.some(method => method.type === 'social');
  }
  hasNative(): boolean {
    return this.supportLoginMethods.some(method => method.type === 'native');
  }

  hasSSOMethods(): boolean {
    return this.supportLoginMethods.some(method => method.type === 'sso');
  }
  getIcon(method: SupportLoginMethod): string {
    return method.icon_url  ? method.icon_url : this.defaultIconClass;
  }

  //grath code
  init():void{
    const token: string |null = this.route.snapshot.queryParamMap.get('token');
    const error: string|null = this.route.snapshot.queryParamMap.get('error');

    if (this.storrage.getItem("token")) {
      this.isLoggedIn = true;
      this.user = this.storrage.getUser();
    }
        else if(token){
                //token present means user is authenticated
                this.storrage.setItem("token",token);
                //get user details
                /*this.userService.getUserData(this.loogedInUser).subscribe(
                      data => {
                        this.login(data);
                      },
                      err => {
                        //this.errorMessage = err.error.message;
                        //this.isLoginFailed = true;

                        this.mssgService.add({ severity: "Error", summary: "Login  ", detail: "User not found ,Please check credentials", });

                      }
                  );
                  */
        }
        else if(error){
//                this.errorMessage = error;
  //          this.isLoginFailed = true;

            //this.mssgService.add({ severity: "Error", summary: "Login  ", detail: "User not found ,Please check credentials", });

        }
  }

  loogedInUser(loogedInUser: any) {
    throw new Error('Method not implemented.');
  }
  login(data: any) {
    throw new Error('Method not implemented.');
  }

  checkIfUsrExist(response)
  {
    try {
      if (response) {
        const data = response.users;

        console.log(data);

        if (typeof data === 'string') {
          // Fix the JSON string and parse it
          const fixedString = data.replace(/\\t/g, '').replace(/\\u0027/g, "'");
  
          try {
              const parsedData = JSON.parse(fixedString);
              console.log("Parsed data:", parsedData);
  
              // Extract the support_login_methods object if it exists
              // Extract the support_login_methods string if it exists
            let supportLoginMethodsString = parsedData.support_login_methods;
            console.log("Support login methods (string format):", supportLoginMethodsString);

            console.log(supportLoginMethodsString.replace("           ","").replace("            ","").replace("            ","").replace("        ",""));
             
            var jsonString = supportLoginMethodsString.replace("           ","").replace("            ","").replace("            ","").replace("        ","")
    
            console.log(jsonString);

            var userData: UserData = AuthDataList; // Fetch userData from your service
            if (userData && userData.support_login_methods) {
              this.supportLoginMethods = userData.support_login_methods.filter(method => method.displayname === 'native');
            }
            
          } catch (error) {
              console.error("Error parsing JSON:", error);
          }
      } else {
          console.error("Error: data is not a string.");
      }
        
      } else {
        console.error("Error: response or response.data is undefined or null.");
      }
    } catch (error) {
      console.error("Error processing response: ", error);
    }
  }

  getUserPermissions(username) {
    this.baseService.getData(`user/getUsrByHandle/${username}`).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          //token present means user is authenticated
          this.storrage.setItem("permissions",data.user.permissions);

          this.storrage.setItem("role",data.user.roles[0]);

          this.storrage.setItem("user",data.user.userId);

          if ("Tenant Admin" == this.storrage.getItem('role')){
            
          }
            

          // const permissions = this.storrage.getItem('permissions')

          // console.log(permissions);
           
          // if(permissions?.includes('Add Tenant'))
          //   {
          //     console.log("Is present");              
          //   }
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  
}
