import { LocationStrategy } from '@angular/common';
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable, mergeMap, of, takeUntil } from 'rxjs';
import { Unsub } from '../class/unsub.class';
import { CustomersService } from '../services/customers/customers.service';
import { LoaderService } from '../services/loader.service';
import { CustomerDataService } from '../services/admin/customer-data.service';
import { CustomerTimeoutGuard } from './customerTimeout.guard';

@Injectable({
  providedIn: 'root',
})
export class CustomerAuthGuardGuard extends Unsub implements CanActivate {
  constructor(
    public router: Router,
    private customerService: CustomersService,
    private customertimeoutGuard: CustomerTimeoutGuard,
    private customerDataService: CustomerDataService,
    private locationStrategy: LocationStrategy,
    loaderService: LoaderService
  ) {
    super(loaderService);
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {
    return this.checkAccess(route, state);
  }

  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {
    return this.checkAccess(childRoute, state);
  }

  private checkAccess(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
    
    return this.customerService.checkLogin().pipe(
      takeUntil(this.unSubscribe$),
      mergeMap((res: any) => {
        this.customerDataService.setSharedData(res?.body);
        let Twofactor = res.headers.get('Twofactor');
        const Google2fa = res.headers.get('Google2fa');
        const email = res.headers.get('email');
        if (Twofactor === 'customer') {
          this.router.navigate(['/customer/customertwofactor/' + email], {
            queryParams: {
              returnUrl: state.url,
            },
          });
          return of(false);
        } else if (Google2fa === 'customer') {
          this.router.navigate(['/customer/customergoogle2fa/' + email], {
            queryParams: {
              returnUrl: state.url,
            },
          });
          return of(false);
        } else if (res.body?.customer) {
          if(res?.body?.redirectionstatus){
            if(res.body.redirectionstatus == 'googletwofact'){
              this.router.navigate([`/customer/customergoogle2fa/${res.body?.email}`]);
            }else if(res.body.redirectionstatus == 'twofactoremail'){
              this.router.navigate([`/customer/customertwofactor/${res.body?.email}`]);
            }
          }else if (state.url.match('/customer/login')) {
              this.router.navigate(['/customer/dashboard']);
          }
          return this.customertimeoutGuard.canActivate(route, state);
        } else if (/customer\/register/gi.test(state.url)) {
          return of(true);
        } else if (!/customer\/login/gi.test(state.url)) {
          this.router.navigate(['/customer/login'], {
            queryParams: {
              returnUrl: state.url,
            },
          });
          return of(true);
        }else{
          return this.customertimeoutGuard.canActivate(route, state);
        }
      })
    );
  }

  /* eslint-disable @typescript-eslint/no-unused-vars */
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {

    history.pushState(null, '');
    this.locationStrategy.onPopState(() => {
      history.go(1);
    });
    return true;
  }
}
