import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Component, HostListener, Input, OnInit, SimpleChanges } from '@angular/core';
import { Observable, concatMap, interval, takeUntil } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { NavigationStart, Router } from '@angular/router';
import { LocationStrategy } from '@angular/common';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Unsub } from '../../../class/unsub.class';
import { AdminService } from '../../../services/admin/admin.service';
import { CaptchaService } from '../../../services/admin/captcha.service';
import { GeneralSettingsService } from '../../../services/admin/general-settings.service';
import { LanguagesService } from '../../../services/admin/languages.service';
import { CustomersService } from '../../../services/customers/customers.service';
import { LoaderService } from '../../../services/loader.service';
import { RecaptchaLoaderService } from 'ng-recaptcha';

@Component({
  selector: 'app-guest-header',
  templateUrl: './guest-header.component.html',
  styleUrls: ['./guest-header.component.scss'],
  providers : [TranslatePipe, RecaptchaLoaderService]
})
export class GuestHeaderComponent extends Unsub implements OnInit {
  password;
  @Input() headerDetails: any;
  homepage = true;
  isMenuCollapsed = true;
  languageDetails;
  captchaStatus: boolean = false;
  public sendingResponse: { [key: string]: boolean } = {};
  public Notificationlength: any;
  public notifications: any;
  public DropDownName: any;
  constructor(
    private adminService: AdminService,
    private modalService: NgbModal,
    private customService: CustomersService,
    private router: Router,
    private toastr: ToastrService,
    private languagesService: LanguagesService,
    private customerService: CustomersService,
    private captchService: CaptchaService,
    public generalSettingsService: GeneralSettingsService,
    private locationStrategy: LocationStrategy,
    private translateservice: TranslateService,
    private translate: TranslatePipe, private sanitizer: DomSanitizer, loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
    this.homepage = this.router?.['url'] == "/" ? true : false;

    this.router.events.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (event: any) => {
        if (event instanceof NavigationStart) {
          this.homepage = event?.['url'] == "/" ? true : false;
        }
      }
    });
    this.languagesService
      .defaultlang()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (defaultlang) => {
          this.languageDetails = defaultlang?.languages;
          this.DropDownName = localStorage.getItem('lang');
          if (this.DropDownName != null) {
            this.translateservice.use(this.DropDownName);
          } else {
            defaultlang?.languages?.map((ele: any) => {
              if (ele.languagecode == defaultlang.default_lang) {
                this.DropDownName = ele.languagename;
                this.translateservice.use(ele.languagecode);
              }
            });
          }
        },
      });

  }

  ngOnChanges(changes: SimpleChanges){
    this.currencySel = this.headerDetails?.selectedcurrencies?.code ?? 'USD';
  }

  setLanCod(cod: any, id: any, lang: any) {
    this.translateservice.use(cod);
    this.DropDownName = lang;
    localStorage.setItem('lang', cod);

    this.adminService.RefreshRquestAdmin$.next();
  }

  playAudio() {

    const audio = new Audio();
    audio.src = './assets/music/sound.mp3';
    audio.load();
    audio.play();
  }

  MarkAllRead() {
    const data = {

    };
    this.customService.markallnotify(data).subscribe();
  }

  MarkAsReadWithID(id: any) {
    const data = {
      id: id,
    };
    this.customService
      .markNotification(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe();
  }


  lastPollTime = 0;
  ngOnInit(): void {
    this.customService.cnotificationsreading().pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.notifications = res?.notifys?.data;

        if (this.Notificationlength != undefined) {
          if (this.Notificationlength < res?.badgecount) {
            this.toastr.success(this.translate.transform('You received a notification'));
            navigator.vibrate([200, 100, 250]);
            this.playAudio();
          }
        }
        this.Notificationlength = res?.badgecount;
      },
    });
    interval(5000).pipe(
      concatMap(() => {
        const currentTime = Date.now();
        if (this.lastPollTime + 1000 <= currentTime) {
          this.lastPollTime += 1000;
          return this.customService.cnotificationsreading();
        } else {
          return new Observable<void>((observer) => {
            observer.complete();
          });
        }
      })
    ).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.notifications = res?.notifys?.data;

        if (this.Notificationlength != undefined) {
          if (this.Notificationlength < res?.badgecount) {
            this.toastr.success(this.translate.transform('You received a notification'));
            navigator.vibrate([200, 100, 250]);
            this.playAudio();
          }
        }
        this.Notificationlength = res?.badgecount;
      },
    });
  }
  open(content) {

    if (this.headerDetails?.customfields) {
      this.headerDetails.customfields.forEach((element) => {
        if (
          (element.fieldtypes == 'radio' ||
            element.fieldtypes == 'checkbox') && element.status == 1
        ) {
          this.customfield['custom_' + element.id] = {
            status: element.fieldrequired,
          };
          if (element.fieldrequired == 1) {
            this.checkStatus = true;
          }
        }
      });
    }

    this.modalService.dismissAll();
    this.modalService
      .open(content, { backdrop: 'static', keyboard: false, size: 'md' })
      .result.then(
        () => {
          this.password = null;
        },
        () => {
          this.password = null;
        }
      );
  }
  toggleMenu() {
    document.body.classList.toggle('active');
  }
  forgotPassword(ngForm, buttonId) {
    this.sendingResponse[buttonId] = true;
    const data = {
      email: ngForm.value.email,
    };
    this.customService
      .forgotPassword(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
            if (res?.['redirect']) {
              this.router.navigate(['/']);
            }
            this.router.navigate(['/customer/login']);
            this.modalService.dismissAll();
          }
          if (res?.error) {
            this.toastr.error(this.translate.transform(res.error));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }

  logoutcustomer(buttonId) {
    this.sendingResponse[buttonId] = true;
    const data = {

    };
    this.customService
      .customerLogout(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success && !res?.redirect) {
            this.toastr.success(this.translate.transform(res.success));
            this.modalService.dismissAll();
            this.router.navigate(['/customer/login']);
            localStorage.clear();

            history.pushState(null, '');
            this.locationStrategy.onPopState(() => {
              history.go(1);
            });
          }
          if (res?.success && res?.redirect) {
            this.toastr.success(this.translate.transform(res.success));
            this.modalService.dismissAll();
            this.router.navigate(['/']);
            localStorage.clear();

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

          if (res?.error) {
            this.toastr.error(this.translate.transform(res.error));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }

  customerLogin(ngForm, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      const data = ngForm.value;
      if (this.headerDetails?.setting?.original?.CAPTCHATYPE=='manual' && this.headerDetails?.setting?.original?.RECAPTCH_ENABLE_LOGIN == 'yes') {
        if (!this.captchaStatus) {
          this.toastr.error(this.translate.transform('Captcha Invalid'));
          this.sendingResponse[buttonId] = false;
          return;
        }
      }
      if (this.captchaStatus) {
        data['captcha'] = 'valid';
      }
      if (this.headerDetails?.setting?.original?.login_disable == 'on') {
        this.toastr.error(this.translate.transform(this.headerDetails?.setting?.original?.login_disable_statement));
        this.sendingResponse[buttonId] = false;
      } else {
        this.customService
          .customerLogin(data)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next:
              (res) => {
                this.sendingResponse[buttonId] = false;
                if (res?.success) {
                  this.toastr.success(this.translate.transform(res.success));
                  this.router.navigate(['/customer/dashboard']);
                  this.modalService.dismissAll();
                  ngForm.reset();
                }
                if (res?.error?.errors) {
                  ngForm.value.password = null;
                  this.password = "";

                  for (const el in res.error.errors) {
                    this.toastr.error(this.translate.transform(res.error.errors[el]));
                  }
                }
                else if(res?.error && res?.email){
                  this.toastr.error(this.translate.transform(res.email));

                } else if (res?.error) {
                  ngForm.value.password = null;
                  this.password = "";
                  this.toastr.error(this.translate.transform(res.error));
                }
                this.captchService.setCaptchaStatus(false);
              },
            error: () => {
              this.sendingResponse[buttonId] = false;
              ngForm.value.password = null;
              this.password = "";
              this.captchService.setCaptchaStatus(false);
            },

          },
          );
      }
    }
  }

  captcha: any;
  public resolved(captchaResponse: string | any): void {
    this.captcha = captchaResponse;
  }

  socialLogin(callback) {
    this.customService.scoialLogin(callback).subscribe(res => {
      if (res?.['redirect']) {
        location.href = res['redirect'];
      }
    });
  }

  // register

  register(ngForm, buttonId) {
    const cf = this.customfield;
    const newCf = {};
    for (const i in cf) {
      const e = cf[i].val;
      newCf[i] = e;
    }
    if (ngForm.valid && !this.checkStatus) {
      this.sendingResponse[buttonId] = true;

      const data = { ...ngForm.value, ...newCf };
      data['agree_terms'] = ngForm.value.agree_terms ? 'agreed' : '';

      if (this.headerDetails?.setting?.original?.CAPTCHATYPE=='manual' && this.headerDetails?.setting?.original?.RECAPTCH_ENABLE_REGISTER == 'yes') {
        if (!this.captchaStatus) {
          this.toastr.error(this.translate.transform('Captcha Invalid'));
          this.sendingResponse[buttonId] = false;
          return;
        }
      }
      if (this.captchaStatus) {
        data['captcha'] = 'valid';
      }
      if (this.headerDetails?.setting?.original?.REGISTER_DISABLE == 'off') {
        this.toastr.error(this.translate.transform(this.headerDetails?.setting?.original?.login_disable_statement));
        this.sendingResponse[buttonId] = false;
      } else {
        this.customService
          .customerRegister(data)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.sendingResponse[buttonId] = false;
              if (res?.success) {
                this.toastr.success(this.translate.transform(res.success));
                this.modalService.dismissAll();
                this.router.navigate(['/customer/login']);
              }
              if (res?.error?.errors) {
                for (const el in res.error.errors) {
                  this.toastr.error(this.translate.transform(res.error.errors[el]));
                }
                this.password = "";
                ngForm.value.password = null;
              } else if (res?.error) {
                this.toastr.error(this.translate.transform(res.error));
                ngForm.value.password = null;
                this.password = "";
              }
              this.captchService.setCaptchaStatus(false);
            },
            error: () => {
              this.sendingResponse[buttonId] = false;
              this.captchService.setCaptchaStatus(false);
            },
          });
      }
    }
  }

  customfield = {};
  checkStatus = false;
  checkCount: any[] = [];
  customfieldSection(res, name, type): void {
    this.checkStatus = true;
    this.checkCount = [];
    if (type == 'radio') {
      this.customfield[name].val = res;
    }
    if (type == 'checkbox') {
      if (this.customfield[name].val?.includes(res)) {
        this.customfield[name].val = this.customfield[name].val.filter((x) => {
          return x != res;
        });
      } else {
        if (this.customfield[name].val) {
          this.customfield[name].val.push(res);
        } else {
          this.customfield[name].val = [res];
        }
      }
    }
    for (const i in this.customfield) {
      if (this.customfield[i].status == 1) {
        if (this.customfield[i]?.val?.length) {
          continue;
        } else {
          this.checkCount.push(this.customfield[i]);
        }
      }
    }
    if (this.checkCount.length) {
      this.checkStatus = true;
    } else {
      this.checkStatus = false;
    }
  }

  scrolled = false;

  @HostListener('window:scroll', [])
  onWindowScroll() {
    this.scrolled = window.scrollY > 64;
  }

  captchaMessage = '';
  manualCaptchEvent(value: any) {
    if(!value?.optional){
      if (value.generated == value.input) {
        this.captchaStatus = true;
        this.captchaMessage = '';
      } else if(value.input == '') {
        this.captchaMessage = 'Enter valid captcha';
        this.captchaStatus = false;
      }else{
        this.captchaStatus = false;
      }
    }
  }

  override ngOnDestroy() {
    this.modalService?.dismissAll();
  }
  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
  currencySel = '';
  setCurrencyCode = (code) => {
    localStorage.setItem('cur', code.code);
    this.currencySel = code.code;
    this.customerService.customerChangeCurrency({ 'currencyId': code.id, 'code': code.code }).subscribe({
      next : res => {
      if (res.success) {
        this.toastr.success(this.translate.transform(res.success));
      }
    }
    })
  }
}
