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 { Router } from '@angular/router';
import { NgbModal, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { Subscription } from 'rxjs';
import { Observable, Subject, debounceTime, distinctUntilChanged, switchMap, takeUntil, tap } 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 { CommonModule } from '@angular/common';
import { MaterialeModules } from '../../../../material.module';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';

@Component({
  selector: 'app-main-categories',
  templateUrl: './main-categories.component.html',
  styleUrls: ['./main-categories.component.scss'],
  standalone : true,
  imports : [CommonModule, AdminPageHeaderComponent, TranslatePipes, MaterialeModules, NgbTooltipModule, FormsModule, NgSelectModule ]
})
export class MainCategoriesComponent extends Unsub implements OnInit {
  public allcategories: any;
  private searchTerms = new Subject<string>();
  public allcategories$!: Subscription;
  envatoAssiged;
  Priority = true;
  groupAssiged;
  public ticketDetails: any;
  public userDetails: any;
  public sendingResponse: { [key: string]: boolean } = {};
  setting;
  displayedColumns: string[] = [
    'id',
    'select',
    'categoryname',
    'ticketknowledge',
    'assigntogroups',
    'assignedpriority',
    'status',
    'actions',
  ];
  dataSource!: MatTableDataSource<any>;
  selection = new SelectionModel<any>(true, []);
  permission: any;
  isloader = true;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  module: any;

  constructor(
    private adminService: AdminService,
    private router: Router,
    private toastr: ToastrService,
    private modalService: NgbModal,
    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.categories();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.categories();

      },
    });

    this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((): any => this.loadData())
    ).subscribe();
  }
  categories() {
    this.isloader = true;
    this.loaderService.showLoader();
    this.allcategories$ = this.adminService
      .categories(1, 10, this.filterValue)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.permission = res.permissions;
          this.allcategories = res.categories;
          this.setting = res.setting?.original;
          // Assign the data to the data source for the table to render
          this.isloader = false;
          this.dataSource = new MatTableDataSource(this.allcategories.data);

          if (this.dataSource) {
            this.paginator.pageSize = this.allcategories.per_page;
            setTimeout(() => {
              this.paginator.pageIndex = this.allcategories.current_page - 1;
              this.paginator.length = this.allcategories.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' || 'ticketdetails' || 'status':
                    return this.nestedProperty(data, sortHeaderId);
                  default:
                    return this.nestedCaseInsensitive(data, sortHeaderId);
                }
              }
          }
          if (!this.permission?.includes('Category Delete')) {
            this.displayedColumns = [
              'id',
              'categoryname',
              'ticketknowledge',
              'assigntogroups',
              'assignedpriority',
              'status',
              'actions',
            ];
          }
          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) {
      numRows = this.dataSource.data.length;
    }
    return numSelected === numRows;
  }
  /** Selects all rows if they are not all selected; otherwise clear selection. */
  toggleAllRows() {
    if (this.isAllSelected()) {
      this.selection.clear();
      return;
    }
    let data = this.dataSource.data.filter(e =>{
      if(!e.groupscategoryc?.length) {return e};
    })
    this.selection.select(...data);
  }

  /** 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
      }`;
  }
  deleteCategories(row: any, 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.adminService
          .categoriesdeleteId(data, row?.id)
          .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;
            },
          });
      }
    });
  }
  assignGroup;
  GroupAssignModel(row, category) {
    this.adminService.groupassigned(row.id).subscribe({
      next: res => {
        this.groupAssiged = res.data;
        this.assignGroup = res;

      }
    });
    const modalRef = this.modalService.open(category, {
      size: 'lg',
      backdrop: 'static', keyboard: false
    });
    modalRef.result.then(
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.assignGroup = '';
        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      },
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.assignGroup = '';

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      }
    );
  }
  createCategoryModel(createCategory) {
    const modalRef = this.modalService.open(createCategory, {
      size: 'lg',
      backdrop: 'static', keyboard: false
    });
    modalRef.result.then(
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.Priority = true;

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      },
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.Priority = true;

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      }
    );
  }
  editCategoriesDetails(editCategory, row) {

    this.newCategory = {
      id: row?.id,
      name: row?.name,
      display: row?.display,
      priority: row?.priority,
      status: row?.status,
    };
    if (row?.display == 'knowledge') {
      this.Priority = false;
    }
    const modalRef = this.modalService.open(editCategory, {
      size: 'lg',
      backdrop: 'static', keyboard: false
    });
    modalRef.result.then(
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.Priority = true;

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      },
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];
        this.Priority = true;

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      }
    );
  }
  newCategory = {
    id: '',
    name: '',
    display: '',
    priority: '',
    status: '',
  };
  categoryCreate(values: any, buttonId) {
    const data = {

      name: values.name,
      display: values.display,
      priority: values.priority,
      status: values.status,
    };
    this.sendingResponse[buttonId] = true;

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

          if (res?.errors) {
            for (const i in res.errors) {
              this.toastr.error(this.translate.transform(res.error[i]));
            }
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
  }
  categoryEdit(ngForm: any, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      const data = {
        "testimonial_id": ngForm.value.testimonial_id,
        "name": ngForm.value.name,
        "display": ngForm.value.display,
        "priority": ngForm.value.priority,
        "status": ngForm.value.status ? 1 : 0,
      };

      this.adminService
        .createCategories(data)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.modalService.dismissAll();
            }
            if (res.errors) {
              this.toastr.error(this.translate.transform(res.errors));
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  categorycategoriesStatusChange(row) {
    const val = row?.status !== '1' ? '1' : '0';

    const data = {

      status: val,
    };
    this.adminService
      .categoriesStatus(row?.id, data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        }
      });
  }
  assignEnvato(assign) {
    this.adminService.categoryList().subscribe({
      next: (res) => {
        this.envatoAssiged = res;
      },
    });
    const modalRef = this.modalService.open(assign,{
      size: 'lg',
      backdrop: 'static', keyboard: false
    });
    modalRef.result.then(
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      },
      () => {
        this.envatoAssiged = [];
        this.groupAssiged = [];

        this.newCategory = {
          id: '',
          name: '',
          display: '',
          priority: '',
          status: '',
        };
      }
    );
  }
  envatoAssignFn(value: any, buttonId) {
    const data = {
      "categorys_id": value.assigned_user_id,
    };
    this.sendingResponse[buttonId] = true;
    this.adminService
      .categoryenvatoassign(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res: any) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
            this.modalService.dismissAll();
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
  }

  massDeleteCategory(buttonId) {
    if (!this.selection.selected.length) {
      this.toastr.error(this.translate.transform('Please select atleast one Category'));
      return;
    }
    const id: any = [];
    this.selection.selected.map(function (ele) {
      id.push(ele.id);
    });
    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
          .categoriesdeleteall(data)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.sendingResponse[buttonId] = false;
              this.selection.clear();
              if (res.success) {
                this.toastr.success(this.translate.transform(res.success));
              }
            },
            error: () => {
               this.sendingResponse[buttonId] = false;
            },
          });
      }
    });
  }

  GroupAssignFn(ngForm, buttonId) {
    this.sendingResponse[buttonId] = true;
    const data = ngForm.value;
    data['category_id'] = this.assignGroup.assign_data.id;
    data['category_name'] = this.assignGroup.assign_data.name;

    this.adminService.groupcategoryGroup(data).subscribe({
      next: res => {
        this.sendingResponse[buttonId] = false;
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
          this.modalService.dismissAll();
        }
      },
      error: () => {
         this.sendingResponse[buttonId] = false;
      },
    });
  }

  priorityFn(arg) {
    if (arg == 'knowledge') {
      this.Priority = false;
    }
    else {
      this.Priority = true;
    }

  }

  loadData(): Observable<any> {
    this.isloader = true;
    return this.adminService.categories(this.paginator.pageIndex + 1, this.paginator.pageSize, this.filterValue).pipe(
      tap((data: any) => {
        this.isloader = false;
        this.dataSource.data = data.categories.data;
        setTimeout(() => {
          this.paginator.pageIndex = data.categories.current_page - 1;
          this.paginator.length = data.categories.total;
          this.paginator.pageSize = data.categories.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;
  };
}
