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 { Observable, Subject, debounceTime, distinctUntilChanged, switchMap, takeUntil, tap } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../shared/class/unsub.class';
import { AdminService } from '../../../shared/services/admin/admin.service';
import { CustomersService } from '../../../shared/services/customers/customers.service';
import { LoaderService } from '../../../shared/services/loader.service';
import { TranslationService } from '../../../shared/services/translation.service';
import { CommonModule } from '@angular/common';
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { MaterialeModules } from '../../../material.module';
import { RouterLink } from '@angular/router';
import { TranslatePipes } from '../../../shared/pipes/translate/translate.pipe';
import { DateAgoPipe } from '../../../shared/pipes/date-ago/date-ago.pipe';

@Component({
  selector: 'app-closed-tickets',
  templateUrl: './closed-tickets.component.html',
  styleUrls: ['./closed-tickets.component.scss'],
  standalone : true,
  imports : [CommonModule, TranslatePipes, MaterialeModules, NgbTooltipModule, RouterLink, DateAgoPipe]
})
export class ClosedTicketsComponent extends Unsub implements OnInit {
  dataSource!: MatTableDataSource<any>;
  public tickets: any;
  private searchTerms = new Subject<string>();
  setting;
  isloader = true;
  refreshToken$;
  selection = new SelectionModel<any>(true, []);
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  displayedColumns: string[] = [
    'id',
    'ticketdetails',
    'status',
    'actions',
  ];
  timezone: any;
  constructor(
    private customersService: CustomersService,
    private adminService: AdminService,
    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.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.closedTickets();
      }
    });
    this.closedTickets();
    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);
  }
  closedTickets() {
    this.loaderService.showLoader();
    this.isloader = true;
    this.customersService
      .dashboardData(1, 10, this.filterValue)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next:
          (data) => {
            this.tickets = data.closed;
            this.setting = data?.setting?.original;
            this.timezone = data.timezonedata;
            // Assign the data to the data source for the table to render
            this.isloader = false;
            this.dataSource = new MatTableDataSource(this.tickets.data);

            if (this.dataSource) {
              this.paginator.pageSize = this.tickets.per_page;
              setTimeout(() => {
                this.paginator.pageIndex = this.tickets.current_page - 1;
                this.paginator.length = this.tickets.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()
          }
      }
      );
  }

  ngOnInit(): void {

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

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

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

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