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 { ActivatedRoute, RouterLink } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import Swal from 'sweetalert2';
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 { NgbRatingModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { LiveChatService } from '../../../../shared/services/admin/livechat.service';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';

@Component({
  selector: 'app-livechat-agent-report-details',
  templateUrl: './livechat-agent-report-details.component.html',
  styleUrls: ['./livechat-agent-report-details.component.scss'],
  standalone: true,
  imports: [AdminPageHeaderComponent, TranslatePipes, MaterialeModules, NgbTooltipModule, RouterLink, NgbRatingModule]
})
export class LivechatAgentReportDetailsComponent extends Unsub implements OnInit {
  public projects: any;
  public users: any;
  private empid!: any;
  public sendingResponse: { [key: string]: boolean } = {};
  displayedColumns: string[] = [
    'sno',
    'rating',
    'problemRectifiedt',
    'feedBackData',
    'actions',
  ];
  dataSource!: MatTableDataSource<any>;
  selection = new SelectionModel<any>(true, []);
  Auth: any;
  isloader;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    private adminService: AdminService,
    private livechatService: LiveChatService,
    private activeRoute: ActivatedRoute,
    private toastr: ToastrService,
    private translate: TranslatePipe,
    private translationService: TranslationService,
    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.employeeReports();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.employeeReports();
      },
    });
  }
  employeeReports() {
    this.loaderService.showLoader();
    this.isloader = true;
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.empid = params.get('id');
        this.livechatService
          .employerRatings(this.empid)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.projects = res.reviewsData;
              this.users = res.users;
              // Assign the data to the data source for the table to render
              this.isloader = false;
              this.dataSource = new MatTableDataSource(this.projects);
              if (this.dataSource) {
                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();
      }
    });
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue?.trim().toLowerCase();

    if (this.dataSource && this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
  deleteagentReview(id, buttonId) {
    const data = {

    };
    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.livechatService.deleteFeedback(id, data).subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
            }
            if (res?.error) {
              this.toastr.error(this.translate.transform(res.error));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
      }
    });
  }

  customerAdminLogin(id) {
    this.livechatService.employerRatings(id).subscribe(res => {
      if (res?.error) {
        this.toastr.error(this.translate.transform(res.error));
      }
      if (res?.success) {
        this.toastr.success(this.translate.transform(res.success));
      }
      if (res?.redirect) {
        window.open(`${window['origin']}${window['$BaseVal']}customer/dashboard`, '_blank');
      }
    });
  }

  onPaginateTable() {
    this.selection.clear();
  }
  // 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;
  };
}
