// Anglar Core
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

// Services
import { LoginService } from '../../services/login/login.service';
import { SessionService } from 'src/app/services/session/session.service';
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { environment } from 'src/environments/environment';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

@Component({
  standalone: false,
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {

  loginForm:any = FormGroup;
  submitted:boolean = false;
  showPassword: boolean = false;
  /**
   * Default config object
   * @type Object
   */
  config:any = {
    showMsg: false,
    errorMessage: ''
  };
  renderMe:boolean = true;
  loginInfo: any = {};
  session!: SessionDataInterface['data'];
  currentYear: number = new Date().getFullYear();
  imgUrl: string = environment.imageUrl;
  /**
   * Data to display in footer
   * @type Object
   */
  footerData: {year: number, sitename: string} = {
    year: this.currentYear,
    sitename: '' // TODO: This needs to come from the database, not hardcoded in here.
  };
  authenticate:boolean = false;

  constructor(
    private formBuilder: FormBuilder,
    private loginService: LoginService, 
    private sessionService: SessionService,  
    private router: Router, 
    private accountInfo: AccountInfoService,
    private localStorageService: LocalStorageService,
    private dataTransmitter: DataTransmitterService,
    private utilitiesService:UtilitiesService
    ) { }

  ngOnInit(): void {
    this.utilitiesService.updateLiveChat();
    this.loginForm = this.formBuilder.group({
      deaNumber: ['', Validators.required],
      password : ['', Validators.required],
      operation : [''],
      cnf_key : [''],
      redirect : [''],
      remember_username : [''],
    });
    this.getUserSession();
  }

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

  /**
   * Get user session and return defer promise
   * @returns {.$q@call;defer.promise}
   */
  checkSession() {
    return new Promise((resolve) => {
      var r = this.sessionService.get();
      r.then(() => {
        this.session = this.sessionService.getSession();
        resolve(this.session);
      });
    })
  };

  /**
   * Check session and redirect the user if true
   * @returns {undefined}
   */
  getUserSession() {
    this.checkSession().then(() => {
      this.footerData.sitename = this.session.sitename;
      this.dataTransmitter.sitename.next(this.session.sitename);
      if (this.session.logged_in) {
        this.loginInfo.reg_step = this.session.reg_step;
        this.loginInfo.message = this.session.message;
        this.loginInfo.is_buyer = this.session.is_buyer;
        this.redirectUser();
      } else {
        this.renderMe = true;
        this.localStorageService.clear();
      }
    }).catch(err => {
      /**if your asynchronous function returns defer.reject()
      instead of defer.resolve() you can catch the error here**/
    });
  };

  /**
   * Redirect user based to registration step, account type and error message
   * @returns {undefined}
   */
  redirectUser() {
    if (this.loginInfo.reg_step > 6) {
      if (this.loginInfo.is_buyer) {
        if (this.loginInfo.message === 'Password was reset') {
          this.router.navigate(['/market/manageAccount'])
          setTimeout( () => {
            // $rootScope.$emit("enableChangePasswordDiv", {});
            this.accountInfo.enableChangePasswordDiv.emit({});
          }, 3500);
        } else {
          var requestUrl = decodeURIComponent(location.search);
          if (requestUrl.indexOf("redirect") !== -1 && requestUrl.substr(requestUrl.indexOf('=') + 1) !== '') {
            var redirectUrl = decodeURI(requestUrl.substr(requestUrl.indexOf('=') + 1)).split('?');
            let params = {};
            if (redirectUrl[0] === '/market/gpoDeals' && !this.loginInfo.trxade_gpo_member) {
              redirectUrl[0] = '/market/brands';
              params = {mdl: 'mp'};
            }
            for (const [key, value] of new URLSearchParams(redirectUrl[1]).entries()) {
              (params as any)[key] = value;
            }
            this.router.navigate([redirectUrl[0]], {queryParams: params});
          } else {
            this.router.navigate(['/market/home'])
          }
        }
      } else {
        if (this.loginInfo.message === 'Password was reset') {
            this.router.navigate(['/market/manageAccount']);
        } else {
            this.router.navigate(['/market/supplier/home']);
        }
      }
    } else {
      //redirect to specific url based on the registration step the user is in
      if (this.loginInfo.reg_step === 1) {
        this.router.navigate(['/market/confirmEmail'])
      }
      if (this.loginInfo.reg_step === 2) {
        this.router.navigate(['/market/storeInfo'])
      }
      if (this.loginInfo.reg_step === 3) {
        this.router.navigate(['/market/questionnaire'])
      }
      if (this.loginInfo.reg_step === 4) {
        this.router.navigate(['/market/eSign'])
      }
      if (this.loginInfo.reg_step === 5) {
        this.router.navigate(['/market/payment'])
      }
      if (this.loginInfo.reg_step === 6) {
        this.router.navigate(['/market/licenseVerification'])
      }
      if (this.loginInfo.reg_step === 7) {
        this.router.navigate(['/market/accountVerify'])
      }
    }
  };

  authenticateUserSubscribe!:Subscription;
  /**
   * return session object as a promise
   * @returns {object.promise|$q@call;defer.promise}
   */
    getAuthUserPromise(deaNumber: string, password: string) {
      return new Promise((resolve, reject) => {
        this.authenticateUserSubscribe = this.loginService.authenticateUser(deaNumber, password)
          .pipe(
            catchError((err: HttpErrorResponse) => {
              return throwError(() => err); // Re-throw the error so it can be caught by subscribe's error handler
            })
          )
          .subscribe({
            next: (res: any) => {
              resolve(res);
            },
            error: (err: HttpErrorResponse) => {
              console.error('Error occurred:', err.status, err.message); // Log the error details
              reject(err); // Reject the promise with the error
            },
            complete: () => {
              // Optional: any cleanup or finalization can be done here
            }
          });
      });
    }

    /**
     * Method to authenticate user
     */
    validateLogin(isSubmit: boolean = true) {
      this.submitted = isSubmit;
      let deaNumber: string = this.loginFormData.deaNumber.value ?? '';
      let password: string = this.loginFormData.password.value ?? '';

      // Validate form before proceeding
      if (this.loginForm.invalid) {
        return;
      }
      if (deaNumber !== '' && password !== '') {
        this.getAuthUserPromise(deaNumber, password)
          .then((res: any) => {
            // Only if the promise is resolved successfully, continue to setUserRoute
            this.loginInfo = res.data;
            this.setUserRoute();
          })
          .catch(err => {
            // If the promise is rejected, handle the error here
            console.error('Error during login:', err.status, err.message);
            this.loginService.errorCallBack(err);
          });
      }
    }

  /**
   * Set redirect when authenticate is true else show error from response
   * @returns {undefined}
   */
  setUserRoute() {
    this.sessionService.reCheckSession();
    this.config.errorMessage = this.loginInfo.errorMessage;
    switch (this.loginInfo.message) {
      case "Active User":
      case "Confirm Email Pending":
      case "Password was reset":
        this.authenticate = true;
        this.redirectUser();
        break;
      case "Temporary Password expired":
      case "User Banned":
      case "Invalid Login details":
      case "User Suspended":
        this.authenticate = false;
        break;
    }
  };
  /**
  * Enable/Disable Password By clicking Eye icon
  */
  toggleShowPassword() {
    this.showPassword = !this.showPassword;
  };

  ngOnDestroy(){
    this.authenticateUserSubscribe?.unsubscribe();
  }

};
