import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit, Renderer2 } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';
import { environment } from 'src/environments/environment';
import * as moment from 'moment';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { securityFunctions } from 'src/app/core/common/security';
import { CookieService } from 'ngx-cookie-service';
import { LoginModel, OTPModel } from 'src/app/core/models/common-model/Sign-in.model';
import { NgOtpInputConfig } from 'ng-otp-input';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {

  constructor(
    private router: Router,
    public ApiServ: API,
    public commonService: CommonFunctionService,
    public titleService: Title,
    public fb: FormBuilder,
    public validationService: ValidationService,
    private http: HttpClient,
    private cookieService: CookieService,
    private renderer: Renderer2,
  ) { }
  SignInForm: FormGroup;
  ResetPswdForm: FormGroup;
  ShowUserVerificationBox = false;
  showPass: boolean = false;
  userInterval;
  errorMessage = '';
  OTPSection = false;
  ForgetPassword = false;
  Email = '';
  UserIpDetails;
  // Timer 
  resendBtn;
  timerBtn;
  timeLeft: number;
  interval;
  NewPaas = false;
  comfirmPass = false;
  ngOnInit(): void {
    sessionStorage.removeItem('excd');
    securityFunctions.resetSessionStoage('lastLogin')
    securityFunctions.resetSessionStoage('LoginUserData')
    securityFunctions.resetSessionStoage('VData')
    securityFunctions.resetSessionStoage('userName')
    securityFunctions.resetSessionStoage('JwtToken')
    securityFunctions.resetSessionStoage('RefreshToken')
    securityFunctions.resetSessionStoage('JwtTokenExpiry')
    securityFunctions.resetSessionStoage('menu')
    this.SignInForm = this.fb.group({
      EmailID: this.validationService.email,
      Password: this.validationService.required,
      OTP: this.validationService.required,
      forgetPassEmail: this.validationService.email
    });
    this.IsPassWordChange = false;
    this.GetIpAddress();
    this.changePasswordCreate();
  };
  SetupPage() {
    this.getLogo()
  }
  orgLogo
  getLogo() {
    const favicon = this.renderer.selectRootElement('link[rel="icon"]', true);
    this.ApiServ.AdminGet('/ForgotPassword/GetOrgLogo').subscribe((res) => {
      if (res != null) if (res["logo"] != null) {
        this.orgLogo = res["logo"];
        sessionStorage.setItem("logo", JSON.stringify(res));
        this.titleService.setTitle('Inventory Management | ' + res.org_name)
        document.documentElement.style.setProperty('--primary-theme', res['primary_color']);
        document.documentElement.style.setProperty('--secondary-theme', res['secondary_color']);
        this.renderer.setAttribute(favicon, 'href', res['favicon'] ? res['favicon'] : './assets/images/TMC.svg');
      } else {
        this.orgLogo = "https://cdn-aos.b-cdn.net/Static/Email/TMC.svg";
      }
    })
  }
  onKeyUp(event) {
    if (event.keyCode == 13 && !this.disableSignInButton) {
      this.SignIn();
    }

  }
  viewPass() {
    this.showPass = !this.showPass;
  }
  // config OTP 
  config: NgOtpInputConfig = {
    allowNumbersOnly: true,
    length: 4,
    isPasswordInput: false,
    disableAutoFocus: true,
    placeholder: '●',
  };

  userId = '';
  disableSignInButton = false;
  SignIn() {
    if (this.SignInForm.get('EmailID').status == "INVALID" || this.SignInForm.get('Password').status == "INVALID") {
      this.validationService.showValidationsMsg(this.SignInForm.get('EmailID'));
      this.validationService.showValidationsMsg(this.SignInForm.get('Password'));
      return;
    }
    this.disableSignInButton = true;
    clearInterval(this.userInterval);
    let val = this.SignInForm.getRawValue();
    let postData = new LoginModel();
    postData.EmailID = val.EmailID;
    postData.Password = val.Password;
    postData.domain = document.location.host;
    // postData.domain = 'extranet.aos-dev.com';
    postData.ProjectId = '2405170833594899108';
    postData.Browser = this.getBrowserName();
    postData.City = this.UserIpDetails.city;
    postData.CountryCode = this.UserIpDetails.countryCode;
    postData.IP = this.UserIpDetails.query;
    postData.Lon = this.UserIpDetails.lon;
    postData.Lat = this.UserIpDetails.lat;
    postData.Proxy = this.UserIpDetails.proxy;
    postData.Platform = this.getPlatform();
    postData.MachineId = this.cookieService.check('MacId') ? this.cookieService.get('MacId') : ''
    postData.time = (this.ApiServ.getAdjustedLocalTime() * 10000 + 621355968000000000).toString()
    localStorage.setItem('UserEmail', val.EmailID);
    let obj = {
      key: securityFunctions.encryptRSA(securityFunctions.rsa_public_key, JSON.stringify(postData)),
    };
    // let domain = 'extranet.aos-dev.com'
    // // let domain = document.location.host;
    // let domainName = domain.replace(/^(https?:\/\/)?/, '');
    // let domain_time = domainName + '~' + new Date().getTime();
    // let key = securityFunctions.rsa_public_key;
    // let encrypted_string = securityFunctions.encryptRSA(key, domain_time).toString();
    // const headers = new HttpHeaders({
    //   'token': encrypted_string,
    // });
    // const options = { headers: headers };
    this.ApiServ.AdminPost('/ExtranetLogin/ValidateLogin', obj).subscribe((res) => {
      if (res !== null) { // Check if res is not null
        this.disableSignInButton = false
        this.CheckUserStatusForLogin(res, true);
      } else {
        this.disableSignInButton = false
        this.router.navigateByUrl("Auth/Login");
      }
    }, error => {
      this.disableSignInButton = false
      this.router.navigateByUrl("Auth/Login");
    });
  };


  // verify
  CheckUserVerification(key_resp) {
    let req = {
      key: key_resp
    }
    // let domain = document.location.host
    // let domainName = domain.replace(/^(https?:\/\/)?/, '');
    // let domain_time = domainName + '~' + new Date().getTime();
    // let key = securityFunctions.rsa_public_key;
    // let encrypted_string = securityFunctions.encryptRSA(key, domain_time).toString();
    // const headers = new HttpHeaders({
    //   // 'Referer': window.location.origin, // Assuming you want to send the current origin as Referer
    //   'token': encrypted_string
    // });
    // const options = { headers: headers };
    this.ApiServ.AdminPost('/UserMachine/CheckUserVerified', req).subscribe(res => {
      if (res) {
        if (res.Status) {
          clearInterval(this.userInterval);
          if (res.VerificationStatus == 'APPROVED') {
            this.SignIn();
          } else if (res.VerificationStatus == 'REJECT') {
            this.ShowUserVerificationBox = false;
            this.OTPSection = false;
            this.errorMessage = 'Access Rejected';
          }
        } else {
          if (res.Message == 'Key Expired.') {
            clearInterval(this.userInterval);
            this.ShowUserVerificationBox = false;
            this.errorMessage = 'Key Expired';
          }
        }
      }
    })
  }

  loginPage() {
    this.ShowUserVerificationBox = false;
    this.OTPSection = false;
    this.ForgetPassword = false;
  }

  //  OTP set
  onOtpChange(otp) {
    this.SignInForm.get('OTP').setValue(otp);
    // if (otp.keyCode == 13 ) {
    //   this.Verify();
    // }
  }
  //  Common verify 
  CheckUserStatusForLogin(res, MFACheck) {
    if (res.Status) {
      this.userId = res.ResponseObject.user_id;
      if (!res.ResponseObject.change_default_password) {
        const expirationDate = new Date();
        expirationDate.setFullYear(expirationDate.getFullYear() + 1);
        res.MachineId && res.MachineId != 'null' ? this.cookieService.set('MacId', res.MachineId, expirationDate) : '';
        if (MFACheck && res.ResponseObject.IsMFAApplicable) {
          if (res.ResponseObject.IsMFAApplicable) {
            this.timerBtn = true;
            this.resendBtn = false;
            this.OTPSection = true;
            this.errorMessage = '';
            this.timeLeft = 60;
            this.startTimer();
            this.Email = localStorage.getItem('UserEmail');
            return
          }
        }
        else {
          if (MFACheck) {
            if (!res.IsVerified) {
              let time = (this.ApiServ.getAdjustedLocalTime() * 10000 + 621355968000000000).toString();
              var url_content = res.ResponseObject.user_id + "-" + res.MachineId.replace(/-/g, "~") + "-" + time;
              let key = securityFunctions.EncryptReq(url_content)
              this.ShowUserVerificationBox = true;
              this.OTPSection = false;
              this.userInterval = setInterval(() => {
                this.CheckUserVerification(key);
              }, 6000);
              let verificationTimeout = 5 * 60 * 1000;
              setTimeout(() => {
                clearInterval(this.userInterval);
              }, verificationTimeout);
              return;
            }
            else {
              this.SetSessionForLogin(res);
            }
          } else {
            this.SetSessionForLogin(res);
            this.commonService.showMessage(res['ResponseObject'], res['Message']);
          }
        };
        // this.getMenus().subscribe(res => {
        //     if (res) {
        //       // sessionStorage.setItem('menu', JSON.stringify(res))
        //       // this.IsOpenDefaultUrl(res);
        //     }
        // })
      } else {
        this.IsPassWordChange = true;
        return
      }
    } else {
      // !res.Status ? this.loginPage() : '';
      if (res.Message == 'token details not saved') {
        this.loginPage()
      }
      this.errorMessage = res.Message
    }
  }

  SetSessionForLogin(res) {
    clearInterval(this.userInterval);
    let date = new Date(moment(res.ResponseObject.last_login).format("YYYY MM DD hh:mm:ss") + " UTC");
    let lastLogin = moment(date.toString()).format("hh:mm:ss, DD MMM YYYY");
    securityFunctions.setSessionStorage('LoginUserData', JSON.stringify(res.ResponseObject));
    sessionStorage.getItem('JwtToken') ? '' : sessionStorage.setItem('JwtToken', res.JwtToken);
    sessionStorage.getItem('RefreshToken') ? '' : sessionStorage.setItem('RefreshToken', res.RefreshToken);
    sessionStorage.getItem('JwtTokenExpiry') ? '' : sessionStorage.setItem('JwtTokenExpiry', res.JwtTokenExpiry);
    this.commonService.FetchExtranetVendorMaster(res.ResponseObject.extranet_vendor_id, false).subscribe(data => {
      if (data) {
        securityFunctions.setSessionStorage('VData', JSON.stringify(data.Result[0]));
      }
    });
    sessionStorage.setItem('userName', res.ResponseObject.first_name);
    sessionStorage.setItem('org_id', res.ResponseObject.org_id);
    sessionStorage.setItem('lastLogin', lastLogin);
    // sessionStorage.setItem('IscancelPNR', res.ResponseObject.IsCancelPnr);
    // sessionStorage.setItem('Is_Void', res.ResponseObject.IsAllowVoidTicket);
    // sessionStorage.setItem('TpinApplicable', res.TpinApplicable);
    // sessionStorage.setItem('T_Activated', res.TpinActivated);
    // sessionStorage.setItem('T_Expired', res.TpinExpired);
    this.ShowUserVerificationBox = false;
    this.OTPSection = false;
    this.router.navigateByUrl("/");
    this.commonService.StartTimer();
  }
  // MFA 
  startTimer() {
    this.interval = setInterval(() => {
      if (this.timeLeft > 0) {
        this.timeLeft--;
      }
      if (this.timeLeft == 0) {
        clearInterval(this.interval);
        this.resendBtn = true;
        this.timerBtn = false;
      }
    }, 1000);
  }

  ReSendOTP() {
    this.SendOTP();
    this.timerBtn = false;
    this.resendBtn = false;
    this.timeLeft = -1;
  };
  SendOTP() {
    this.ApiServ.AdminGet('/OTP/ResendOTP/' + this.userId).subscribe(
      (data) => {
        if (data) {
          this.commonService.showMessage(data['resp'], data['respMsg']);
        }
      }
    );
  };
  getMenus() {
    return this.http.get(environment.APIBaseUrl + '/MenuMasterNew/GetAllMenuByUserId/' + sessionStorage.getItem('userId') + '/2405170833594899108')
  }
  Verify() {
    if (this.SignInForm.get('OTP').status == "INVALID") {
      this.errorMessage = 'Please enter valid OTP'
      return;
    }
    let val = this.SignInForm.getRawValue();
    let postData = new OTPModel();
    postData.oTP = val.OTP;
    postData.userId = this.userId;
    postData.browser = this.getBrowserName();
    postData.city = this.UserIpDetails.city;
    postData.countryCode = this.UserIpDetails.countryCode;
    postData.iP = this.UserIpDetails.query;
    postData.lon = this.UserIpDetails.lon;
    postData.lat = this.UserIpDetails.lat;
    postData.proxy = this.UserIpDetails.proxy;
    postData.ProjectId = '2405170833594899108';
    postData.platform = this.getPlatform();
    postData.macId = this.cookieService.check('MacId') ? this.cookieService.get('MacId') : '';
    this.ApiServ.AdminPost('/OTP/VerifyOTP', postData).subscribe(res => {
      if (res) {
        this.CheckUserStatusForLogin(res, false);
      } else {
        this.router.navigateByUrl("Auth/Login");
      }
    })
  };
  // forget Password
  SendMail() {
    if (this.SignInForm.get('forgetPassEmail').status == "INVALID") {
      this.validationService.showValidationsMsg(this.SignInForm.get('forgetPassEmail'));
      return;
    }
    let val = this.SignInForm.get('forgetPassEmail').value;
    let request = {
      email: val,
      domain: window.location.origin,
      time: (this.ApiServ.getAdjustedLocalTime()).toString()
    };
    let obj = {
      key: securityFunctions.encryptRSA(securityFunctions.rsa_public_key, JSON.stringify(request)),
    };
    this.ApiServ.AdminGoPost('/ExtranetUserMaster/ValidateEmail', obj).subscribe(
      (data) => {
        if (data) {
          this.commonService.showMessage(data['Resp'], data['Message']);
        }
      }
    );
  };
  // get user details
  getPlatform() {
    var platform = "";
    const userAgent = window.navigator.userAgent.toLowerCase();
    if (/android/i.test(userAgent)) {
      platform = 'Android device';
    } else if (/iphone|ipad|ipod/i.test(userAgent)) {
      platform = 'iOS device';
    } else if (/windows phone/i.test(userAgent)) {
      platform = 'Windows phone';
    } else if (/win/i.test(userAgent)) {
      platform = 'Windows desktop';
    } else if (/mac/i.test(userAgent)) {
      platform = 'Mac desktop';
    } else if (/linux/i.test(userAgent)) {
      platform = 'Linux desktop';
    } else {
      platform = 'Unknown device';
    }
    return platform;
  }
  // getBrowser() {
  //   var browserName = '';
  //   var userAgent = navigator.userAgent;

  //   if (userAgent.indexOf('Firefox') > -1) {
  //     browserName = 'Mozilla Firefox';
  //   } else if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) {
  //     browserName = 'Opera';
  //   } else if (userAgent.indexOf('Trident') > -1) {
  //     browserName = 'Microsoft Internet Explorer';
  //   } else if (userAgent.indexOf('Edge') > -1) {
  //     browserName = 'Microsoft Edge';
  //   } else if (userAgent.indexOf('Chrome') > -1) {
  //     browserName = 'Google Chrome';
  //   } else if (userAgent.indexOf('Safari') > -1) {
  //     browserName = 'Apple Safari';
  //   }

  //   return browserName;
  // }

  getBrowserName(): string {
    const userAgent = navigator.userAgent;
    if (userAgent.includes("Chrome")) {
      return "Google Chrome";
    } else if (userAgent.includes("Firefox")) {
      return "Mozilla Firefox";
    } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) {
      return "Apple Safari";
    } else if (userAgent.includes("Edge")) {
      return "Microsoft Edge";
    } else if (userAgent.includes("OPR") || userAgent.includes("Opera")) {
      return "Opera";
    } else if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {
      return "Internet Explorer";
    } else {
      return "Unknown Browser";
    }
  }

  // Example usage:
  GetIpAddress() {
    this.http.get("https://pro.ip-api.com/json/?fields=query,countryCode,lat,lon,city,proxy&&key=JZDsrdeBzIM0yyN").subscribe(res => {
      if (res) {
        this.UserIpDetails = res;
        let obj = {
          city: res['city'],
          countryCode: res['countryCode'],
          lat: res['lat'],
          lon: res['lon'],
          proxy: res['proxy'],
          iP: res['query'],
        };
        this.SetupPage();
        sessionStorage.setItem('IP', JSON.stringify(obj));
      }
    })
  };

  // common function
  addRemoveValid(name, check) {
    if (check) {
      this.SignInForm.get(name).addValidators([Validators.required]);
    } else {
      this.SignInForm.get(name).clearValidators();
    }
    this.SignInForm.get(name).updateValueAndValidity();
    this.SignInForm.get(name).markAsUntouched();
  };

  // Tpin
  // CheckTpinAllowOrNot(response) {
  //   if (response.TpinApplicable) {
  //     if (!response.TpinActivated || response.TpinExpired) {
  //       const now = new Date();
  //       const formattedDate = now.toISOString().slice(0, 19).replace('T', ' ');
  //       let keyVal = securityFunctions.EncryptReq(response.ResponseObject.user_id + '~' + formattedDate + '~' + (response.TpinExpired ? 'expired' : 'create')).trim()
  //       this.router.navigate(['/Login/TPIN'], { queryParams: { key: keyVal } });
  //       return false
  //     }
  //   }
  //   return true
  // }

  password_criteria_obj = {
    is_lowerCase: false,
    is_Uppercase: false,
    is_Capital_case: false,
    is_numbers: false,
    is_special_characters: false,
    is_length: false
  };
  IsPassWordChange = false;
  changePasswordCreate() {
    this.password_criteria_obj = {
      is_lowerCase: false,
      is_Uppercase: false,
      is_Capital_case: false,
      is_numbers: false,
      is_special_characters: false,
      is_length: false
    };
    this.ResetPswdForm = this.fb.group({
      Password: this.validationService.passwordV2,
      confirm_password: this.validationService.required,
    });
  }
  password_criteria(password_Value) {
    password_Value.length >= 8 ? this.password_criteria_obj.is_length = true : this.password_criteria_obj.is_length = false;
    password_Value.match(this.validationService.regExps.lower_case) ? this.password_criteria_obj.is_lowerCase = true : this.password_criteria_obj.is_lowerCase = false;
    password_Value.match(this.validationService.regExps.Capital_case) ? this.password_criteria_obj.is_Uppercase = true : this.password_criteria_obj.is_Uppercase = false;
    password_Value.match(this.validationService.regExps.numbers) ? this.password_criteria_obj.is_numbers = true : this.password_criteria_obj.is_numbers = false;
    password_Value.match(this.validationService.regExps.special_characters) ? this.password_criteria_obj.is_special_characters = true : this.password_criteria_obj.is_special_characters = false;
  };

  // ResetPassword() {
  //   if (this.ResetPswdForm.status == 'INVALID') {
  //     this.validationService.showValidationsMsg(this.ResetPswdForm);
  //     return;
  //   }
  //   let reset_pswd_obj_val = this.ResetPswdForm.getRawValue();
  //   if (reset_pswd_obj_val.Password != reset_pswd_obj_val.confirm_password) {
  //     this.commonService.showMessage(false, 'Your password does not match with confirm password')
  //     return;
  //   }
  //   let PostData = {
  //     "user_id": this.userId,
  //     "password": reset_pswd_obj_val.Password,
  //     "change_default_password": false
  //   }
  //   let encryptRSAData = {
  //     key: securityFunctions.encryptRSA(securityFunctions.rsa_public_key, JSON.stringify(PostData)),
  //   };
  //   this.http.post<any>(environment.APIBaseUrl + '/StaffMaster/ResetStaffPasswordHome', encryptRSAData).subscribe(res => {
  //     if (res.resp) {
  //       this.commonService.showMessage(true, 'Your password has been changed successfully.');
  //       this.IsPassWordChange = false;
  //     }
  //     else {
  //       this.commonService.showMessage(res.resp, res.respMsg);
  //     }
  //   })
  // }


  // 
  // IsOpenDefaultUrl(data) {
  //   let agency = data.find(e => e.menu_id == '2306211409428416327');
  //   let flight_booking = data.find(e => e.menu_id == '2307251023313127095');
  //   let hotel_booking = data.find(e => e.menu_id == '2307251027232645472');
  //   let flight_transaction = data.find(e => e.menu_id == '2307251045530701040');
  //   let lead_management = data.find(e => e.menu_id == '2307251305094097395');
  //   if (agency) this.navigateMenuLink(agency);
  //   else if (flight_booking) this.navigateMenuLink(flight_booking);
  //   else if (hotel_booking) this.navigateMenuLink(hotel_booking);
  //   else if (lead_management) this.navigateMenuLink(lead_management);
  //   else if (flight_transaction) this.navigateMenuLink(flight_transaction);
  //   else this.router.navigateByUrl("/Home/Dashboard");
  // }
  navigateMenuLink(menu) {
    let url = '/' + menu.ui_controller + '/' + menu.ui_action;
    if (url) {
      sessionStorage.setItem('selMenu', url);
      window.location.href = window.location.origin + url;
    }
  };

  onKeyup(event: KeyboardEvent) {
    if (event.keyCode === 13) { // If Enter key is pressed
      this.SendMail();
    }
  }

}
