import { CommonModule, DatePipe } from '@angular/common';
import { takeUntil } from 'rxjs';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
import Swal from 'sweetalert2';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
@Component({
  selector: 'app-all-notifications',
  templateUrl: './all-notifications.component.html',
  styleUrls: ['./all-notifications.component.scss'],
  standalone : true,
  imports : [CommonModule, AdminPageHeaderComponent, TranslatePipes, FormsModule, RouterLink ],
  providers: [DatePipe]
})
export class AllNotificationsComponent extends Unsub implements OnInit {
  @ViewChild('commentsClose') commentsClose!: ElementRef;
  allNotificationList: any;
  setting;
  today: string | null;
  yesterday: any = new Date();
  public sendingResponse: { [key: string]: boolean } = {};
  authtimezone: any;
  authname: any;
  totalnotifications: any;
  notifysearch: any = null;
  constructor(
    private adminService: AdminService,
    private datePipe: DatePipe,
    private toastr: ToastrService,
    private translate: TranslatePipe,
    loaderService: LoaderService,
    private sanitizer: DomSanitizer
  ) {
    /**
    * 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.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        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'
    );
  }
  statusnotify: any[] = [];

  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();
      },
    });
  }
  allNotifications() {
    this.loaderService.showLoader();
    this.adminService
      .allNotifications(1, JSON.stringify(this.statusnotify), this.notifysearch)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.authtimezone = res.authtimezone;
          this.authname = res.authname;
          this.setting = res.setting?.original;
          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 lastDate: string | null = null;
  shouldShowDateBadge(currentDate: string): boolean {
    if (currentDate !== this.lastDate) {
      this.lastDate = currentDate;
      return true;
    }
    return false;
  }
  private intersectionObserver!: IntersectionObserver;
  public isLoadingComments: boolean = false;
  ngAfterViewInit() {
    this.intersectionObserver = new IntersectionObserver((entries) => {
      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.adminService.allNotifications(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, buttonId) {
    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.sendingResponse[buttonId] = true;

        this.adminService
          .deletenotify(data)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.sendingResponse[buttonId] = false;
              if (res?.success) {
                this.toastr.success(this.translate.transform(res.success));
              }
            },
            error: () => {
               this.sendingResponse[buttonId] = false;
            },
          });
      }
    });
  }

  override ngOnDestroy() {
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
    }
  }
  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
