import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable, concatMap, interval, takeUntil } from 'rxjs';
import { NgbCollapseModule, NgbDropdownModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';
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 { LanguagesService } from '../../../services/admin/languages.service';
import { CustomersService } from '../../../services/customers/customers.service';
import { LoaderService } from '../../../services/loader.service';
import { TranslatePipes } from '../../../pipes/translate/translate.pipe';
import { FormsModule } from '@angular/forms';
import { DateAgoPipe } from '../../../pipes/date-ago/date-ago.pipe';

@Component({
  selector: 'app-customer-header',
  standalone: true,
  imports: [TranslatePipes, NgbDropdownModule, FormsModule, RouterLink, DateAgoPipe, NgbCollapseModule],
  templateUrl: './customer-header.component.html',
  styleUrls: ['./customer-header.component.scss'],
})
export class CustomerHeaderComponent extends Unsub implements OnInit {
  @Input() headerDetails: any;

  captchaStatus: any = '';
  public sendingResponse: { [key: string]: boolean } = {};
  isMenuCollapsed = true;
  public Notificationlength: any;
  public notifications: any;
  public languageDetails: any;
  public DropDownName: any;
  constructor(
    private customerService: CustomersService,
    private adminService: AdminService,
    private languagesService: LanguagesService,
    private toastr: ToastrService,
    private router: Router,
    private modalService: NgbModal,
    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.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);
              }
            });
          }
        },
      });
  }

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

  toggleMenu() {
    document.body.classList.toggle('active');
  }
  playAudio() {
    const audio = new Audio();
    audio.src = './assets/music/sound.mp3';
    audio.load();
    audio.play();
  }

  MarkAllRead() {
    const data = {

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

  MarkAsReadWithID(id: any) {
    const data = {
      id: id,
    };

    this.customerService
      .markNotification(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe();
  }
  lastPollTime = 0;
  ngOnInit(): void {

    this.customerService.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.customerService.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;
      },
    });
  }

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

    };
    this.customerService
      .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.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.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;
        },
      });
  }

  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;
    }
  }

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

  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));
      }
    }
    })
  }
}
