import { SelectionModel } from '@angular/cdk/collections';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { NgbModal, NgbModalModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { Observable, Subject, debounceTime, distinctUntilChanged, switchMap, takeUntil, tap } from 'rxjs';
import Swal from 'sweetalert2';
import { FormsModule, NgForm } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { CommonModule, Location } from '@angular/common';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { TranslationService } from '../../../../shared/services/translation.service';
import { MaterialeModules } from '../../../../material.module';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.scss'],
  standalone : true,
  imports : [CommonModule, AdminPageHeaderComponent, TranslatePipes, MaterialeModules, NgbTooltipModule, RouterLink, NgbModalModule, FormsModule  ]
})
export class EmployeesListComponent extends Unsub implements OnInit {
  Auth: any;
  private searchTerms = new Subject<string>();
  public sendingResponse: { [key: string]: boolean } = {};
  permission: any;
  isloader = true;
  pswd = true;
  refreshToken$;
  public employeeId!: number;
  newPassword: any;
  rolesList: any;
  departmentList: any;
  //subscription list end

  displayedColumns: string[] = [
    'sno',
    'select',
    'employeename',
    'roles',
    'registerDate',
    'status',
    'actions',
  ];
  dataSource!: MatTableDataSource<any>;
  selection = new SelectionModel<any>(true, []);
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  employeeUserData: any;
  countries: any;
  timezones: any;
  constructor(
    private adminService: AdminService,
    private modalService: NgbModal,
    private toastr: ToastrService,
    private router: Router,
    private translate: TranslatePipe,
    private translationService: TranslationService,
    private state: Location,
    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.translationService.TranslationStatus.subscribe(() => {
      setTimeout(() => {
        this.paginator._intl.itemsPerPageLabel = this.translate.transform('items per page:');
        this.paginator._intl.nextPageLabel = this.translate.transform('next');
        this.paginator._intl.previousPageLabel = this.translate.transform('previous');
        this.paginator._intl.firstPageLabel = this.translate.transform('first page');
        this.paginator._intl.lastPageLabel = this.translate.transform('last page');
        const of = this.translate.transform('of');
        this.paginator._intl.getRangeLabel = (page: number, pageSize: number, length: number) => {
          if (length == 0 || pageSize == 0) return `0 ${of} ${length}`;
          length = Math.max(length, 0);
          const startIndex = page * pageSize;
          const endIndex = startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize;

          return `${startIndex + 1} - ${endIndex} ${of} ${length}`;
        };
      }, 100);
    });
    this.translationService.setTranslationaStatus(true);
  }

  ngOnInit(): void {
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.employeeList();
      },
    });
    this.employeeList();

    this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((): any => this.loadData())
    ).subscribe();
  }

  private employeeList() {
    this.loaderService.showLoader();
    this.isloader = true;
    this.adminService
      .employeeList(1, 10, this.filterValue)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (ele: any) => {
          this.Auth = ele.authId;
          this.permission = ele.permissions;
          this.employeeUserData = ele.queryList;
          this.rolesList = ele.roles;
          this.countries = ele.countries;
          this.timezones = ele.timezones;
          this.departmentList = ele.departments;
          // Assign the data to the data source for the table to render
          this.isloader = false;
          this.dataSource = new MatTableDataSource(this.employeeUserData.data);

          if (this.dataSource) {
            this.paginator.pageSize = this.employeeUserData.per_page;
            setTimeout(() => {
              this.paginator.pageIndex = this.employeeUserData.current_page - 1;
              this.paginator.length = this.employeeUserData.total;
            });
            this.dataSource.paginator = this.paginator;
            
              // this.sort.disableClear = true; // Used to disbale the original soting of data if enabled (Only ASC, DES).
              this.dataSource.sort = this.sort;
              this.dataSource.sortingDataAccessor = (data, sortHeaderId) => {
                switch (sortHeaderId) {
                  case 'user':
                  case 'ticketdetails':
                  case 'status':
                    return this.nestedProperty(data, sortHeaderId);
                  default:
                    return this.nestedCaseInsensitive(data, sortHeaderId);
                }
              }
          }
          this.loaderService.hideLoader();
        },
       error: () => {this.isloader = true;  this.loaderService.hideLoader()}
      });
  }

  filterValue = "";
  applyFilter(event: Event) {
    this.filterValue = (event.target as HTMLInputElement).value;
    this.searchTerms.next(this.filterValue);
  }

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    let numRows;
    if (this.dataSource) {
  
      const slicedval = this.dataSource.data;

      numRows = [...slicedval].filter(employess => employess.id != 1 && employess.id != this.Auth).length;

    }
    return numSelected === numRows;
  }
  /** Selects all rows if they are not all selected; otherwise clear selection. */
  toggleAllRows() {
    if (this.isAllSelected()) {
      this.selection.clear();
      return;
    }

    const slicedval = this.dataSource.data;

    const newval = [...slicedval].filter(employess => employess.id != 1 && employess.id != this.Auth);
    this.selection.select(...newval);

  }

  /** The label for the checkbox on the passed row */
  checkboxLabel(row?: any): string {
    if (!row) {
      return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row?.id + 1
      }`;
  }

  resetPopup(content: any, id: number) {
    this.employeeId = id;
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
        this.newPassword = '';
      },
      () => {
        this.newPassword = '';
      }
    );
  }
  resetPassword(ngForm: NgForm, buttonId) {
    const data = {
      "sprukopasswordreset_id": ngForm.value.sprukopasswordreset_id,
      "resetpassword": ngForm.value.resetpassword,
    };
    this.sendingResponse[buttonId] = true;

    this.adminService
      .employeepasswordreset(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (response) => {
          this.sendingResponse[buttonId] = false;
          if (response?.success) {
            this.toastr.success(this.translate.transform(response.success));
            if (response.redirect) {
              this.router.navigate(['/admin/login'], {
                queryParams: {
                  returnUrl: this.state.path(),
                },
              });
            }
            this.modalService.dismissAll();
            ngForm.reset();
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
  }
  statusEmployee(id: any, status, buttonId) {
    const statu = status == 0 ? 1 : 0;
    const data = {

      id: id,
      status: statu,
    };
    this.sendingResponse[buttonId] = true;
    this.adminService
      .employeestatus(data, id)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (response) => {
          this.sendingResponse[buttonId] = false;
          if (response && response?.success) {
            this.toastr.success(this.translate.transform(response.success));
            this.modalService.dismissAll();
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
  }
  deleteEmployee(id: any, buttonId) {
    const data = {

      id: id,
    };
    Swal.fire({
      text: this.translate.transform('Are you sure you want to delete this employee'),
      icon: 'warning',
      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
          .employeedelete(data, id)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (response) => {
              this.sendingResponse[buttonId] = false;
              if (response && response?.success) {
                this.toastr.success(this.translate.transform(response.success));
                this.modalService.dismissAll();
              }
            },
            error: () => {
               this.sendingResponse[buttonId] = false;
            },
          });
      }
    });
  }
  deleteMassEmployee(buttonId) {
    if (!this.selection.selected.length) {
      this.toastr.error(this.translate.transform('Please select atleast one Employeee'));
      return;
    }
    const id: any = [];
    this.selection.selected.map(function (ele) {
      id.push(ele.enc_id);
    });
    const data = {
      id: id,
    };
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure you want to delete this employees?'),
      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
          .employeedeleteAll(data)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (response) => {
              this.sendingResponse[buttonId] = false;
              this.selection.clear();
              if (response && response?.success) {
                this.toastr.success(this.translate.transform(response.success));
                this.modalService.dismissAll();
              }
            },
            error: () => {
               this.sendingResponse[buttonId] = false;
            },
          });
      }
    });
  }

  addTagFn(name: any) {
    return name;
  }

  generatePswd() {
    this.newPassword =
      Math.random().toString(36).slice(2) +
      Math.random().toString(36).toUpperCase().slice(2);
  }

  loadData(): Observable<any> {
    this.isloader = true;
    return this.adminService.employeeList(this.paginator.pageIndex + 1, this.paginator.pageSize, this.filterValue).pipe(
      tap((data: any) => {
        this.isloader = false;
        this.dataSource.data = data.queryList.data;
        setTimeout(() => {
          this.paginator.pageIndex = data.queryList.current_page - 1;
          this.paginator.length = data.queryList.total;
          this.paginator.pageSize = data.queryList.per_page;
        });
      }));
  }

  onPaginateTable() {
    this.selection.clear();
    this.loadData().subscribe();
  }
  override ngOnDestroy() {
    this.modalService?.dismissAll();
  }
  // this is needed to allow sorting on nested properties
  nestedProperty = (data: any, sortHeaderId: string): string | number => {
    return sortHeaderId
      ?.split('.')
      .reduce((accumulator, key) => accumulator && accumulator[key], data) as
      | string
      | number;
  };
  // this is needed to have caseInsensitive sorting
  caseInsensitive = (data: any, sortHeaderId: string): string | number => {
    const value = data[sortHeaderId];
    return typeof value === 'string' ? value.toUpperCase() :
      value;
  };
  nestedCaseInsensitive = (data: any, sortHeaderId: string): string | number => {
    const value = sortHeaderId
      ?.split('.')
      .reduce((accumulator, key) => accumulator && accumulator[key], data) as
      | string
      | number;
    return typeof value === 'string' ? value.toUpperCase() : value;
  };
}
