import { CommonModule, DatePipe } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { fromEvent, takeUntil } from 'rxjs';
import Swal from 'sweetalert2';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../../shared/class/unsub.class';
import { CustomersService } from '../../../../shared/services/customers/customers.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { RouterLink } from '@angular/router';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { TimezonePipe } from '../../../../shared/pipes/timzone.pipe';

@Component({
  selector: 'app-allnotifications',
  templateUrl: './allnotifications.component.html',
  styleUrls: ['./allnotifications.component.scss'],
  standalone : true,
  imports : [CommonModule, TranslatePipes, RouterLink, TimezonePipe],
  providers: [DatePipe]
})
export class AllnotificationsComponent extends Unsub implements OnInit {
  @ViewChild('commentsClose') commentsClose!: ElementRef;
  
  public sendingResponse: { [key: string]: boolean } = {};
  allNotificationList: any;
  totalnotifications: any;
  statusnotify: any[] = [];
  notifysearch: any = null;
  user;
  setting;
  today: string | null;
  yesterday: any = new Date();
  timezone: any;
  constructor(private customerService: CustomersService, private datePipe: DatePipe, private translate: TranslatePipe,
    loaderService: LoaderService,  private sanitizer: DomSanitizer, private toastr: ToastrService) {
    /**
    * 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.allNotifications();

    this.today = datePipe.transform(Date.now(), 'yyyy-MM-dd');
    this.yesterday = datePipe.transform(this.yesterday.setDate(this.yesterday.getDate() - 1), 'yyyy-MM-dd');
  }

  ngOnInit(): void {
    const notifyCheckBox = document.querySelectorAll('.notifystatus');
    const notifySearchInp: any = document.querySelector('.notifysearch');
    const notifysearch = fromEvent(notifySearchInp, 'keyup');
    notifysearch.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (event: any) => {
        // const data = {
        this.notifysearch = event.target.value;
        this.allNotifications();
      },
    });
    const notifystatus = fromEvent(notifyCheckBox, 'click');
    notifystatus.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: () => {
        this.statusnotify = [];
        document.querySelectorAll("input[name='notifystatus[]']:checked").forEach((event) => {
          this.statusnotify.push(event['value']);
        });
        this.allNotifications();
      },
    });

  }

  private lastDate: string | null = null;
  shouldShowDateBadge(currentDate: string): boolean {
    if (currentDate !== this.lastDate) {
      this.lastDate = currentDate;
      return true;
    }
    return false;
  }

  allNotifications() {
    this.loaderService.showLoader();
    this.customerService.allNotification(1, JSON.stringify(this.statusnotify), this.notifysearch).pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: res => {
        this.user = res.authId;
        this.setting = res.setting?.original;
        this.timezone = this.setting.default_timezone;
        this.totalnotifications = res.notifications.total;
        this.pageCount = res.notifications.current_page + 1;
        this.allNotificationList = res.notifications.data;
        this.loaderService.hideLoader();
      },
      error: () => this.loaderService.hideLoader()
    });
  }

  private intersectionObserver!: IntersectionObserver;
  public isLoadingComments: boolean = false;
  ngAfterViewInit() {
    this.intersectionObserver = new IntersectionObserver((entries) => {
      console.log(entries[0].isIntersecting, this.isLoadingComments, this.allNotificationList?.length ,this.totalnotifications );
      
      if (entries[0].isIntersecting && !this.isLoadingComments && this.allNotificationList?.length < this.totalnotifications) {
        this.loadComments();
        this.isLoadingComments = true;
      }
    }, { threshold: 0 });
    const myElement = this.commentsClose.nativeElement;
    this.intersectionObserver.observe(myElement);
  }
  pageCount;

  loadComments() {

    this.customerService.allNotification(this.pageCount, JSON.stringify(this.statusnotify), this.notifysearch)
      .subscribe((res: any) => {
        this.isLoadingComments = false;
        this.pageCount = res.notifications.current_page + 1;
        this.allNotificationList = [...this.allNotificationList, ...res.notifications.data];
      });
  }

  deletenotify(id: any) {

    const data = {

      id: id,
    };
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure ?'),
      text: this.translate.transform('Your will not be able to recover!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, delete it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.customerService
          .deletenotify(data).pipe(
            takeUntil(this.unSubscribe$)
          )
          .subscribe({
            next: (res) => {
              if(res?.success){
                this.toastr.success(res?.success)
                this.allNotifications();
              }
            }
          });
      }
    });
  }
  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
