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, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, FormsModule } from '@angular/forms';
import { HttpHeaders } from '@angular/common/http';
import Swal from 'sweetalert2';
import { TranslatePipe } from '@ngx-translate/core';
import { Subject, takeUntil, debounceTime, distinctUntilChanged, switchMap, Observable, tap } from 'rxjs';
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';
import { ImageUploadComponent } from '../../../../shared/common/includes/image-upload/image-upload.component';

@Component({
  selector: 'app-testimonial',
  templateUrl: './testimonial.component.html',
  styleUrls: ['./testimonial.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, MaterialeModules, NgbTooltipModule, ImageUploadComponent, FormsModule]
})
export class TestimonialComponent extends Unsub implements OnInit {
  basic;
  private searchTerms = new Subject<string>();
  public sendingResponse: { [key: string]: boolean } = {};
  form: FormGroup;
  form2: FormGroup;
  displayedColumns: string[] = [
    'sno',
    'select',
    'name',
    'designation',
    'actions',
  ];
  dataSource!: MatTableDataSource<any>;
  selection = new SelectionModel<any>(true, []);
  permission: any;
  isloader = true;
  loading = true;
  setting;
  refreshToken$;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  testimonials: any;

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

      },
    });

    this.form = this.fb.group({
      image: null,
    });
    this.form2 = this.fb.group({
      image: null,
    });

    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.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((): any => this.loadData())
    ).subscribe();
  }

  testimonialFn() {
    this.isloader = true;
    this.loaderService.showLoader();
    this.adminService
      .testimonialSection(1, 10, this.filterValue)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.permission = res.permissions;
          this.basic = res.basic;
          this.isloader = false;
          this.loading = false;
          this.testimonials = res.queryList;
          this.setting = res.setting?.original;
          this.dataSource = new MatTableDataSource(this.testimonials.data);

          if (this.dataSource) {
            this.paginator.pageSize = this.testimonials.per_page;
            setTimeout(() => {
              this.paginator.pageIndex = this.testimonials.current_page - 1;
              this.paginator.length = this.testimonials.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('Testimonial Delete')) {
            this.displayedColumns = ['sno', 'name', 'designation', 'actions'];
          }
          this.loaderService.hideLoader();
        },
       error: () => {this.isloader = true;  this.loaderService.hideLoader()}
      }); 
  }

  testimonialSectionUpdate(ngForm, buttonId) {
    if (ngForm.valid) {
      const data = {
        id: ngForm.value.id,
        testimonialtitle: ngForm.value.testimonialtitle,
        testimonialsub: ngForm.value.testimonialsub,
      };
      if (ngForm.value.testimonialcheck || ngForm.value.testimonialcheck == 'on') {
        data['testimonialcheck'] = ngForm.value.testimonialcheck;
      }
      this.sendingResponse[buttonId] = true;
      this.adminService
        .testimonialSectionUpdate(data)
        .pipe(takeUntil(this.unSubscribe$))
        .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.errors.message));
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    }
  }

  
  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;
    }

    this.selection.select(...this.dataSource.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
      }`;
  }

  createModelPopup(content: any) {
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false, size: 'lg' });
    modalRef.result.then(
      () => {
        this.form.reset({});
        this.form2.reset({});
        this.testimonialimgRemoved = [];
        this.ticketName = [];
        this.ticketName2 = [];
      },
      () => {
        this.form.reset({});
        this.form2.reset({});
        this.testimonialimgRemoved = [];
        this.ticketName = [];
        this.ticketName2 = [];
      }
    );
  }
  pagesModel = {
    testimonialId: '',
    name: '',
    description: '',
    designation: '',
    image: '',
    profileimage: '',
  };
  editModelPopup(content: any, row: any) {
    this.pagesModel.testimonialId = row.id;
    this.pagesModel.name = row.name;
    this.pagesModel.description = row.description;
    this.pagesModel.designation = row.designation;
    this.pagesModel.image = row.image;
    this.pagesModel.profileimage = row.profileimage;
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false, size: 'lg' });
    modalRef.result.then(
      () => {
        this.pagesModel.testimonialId = '';
        this.pagesModel.name = '';
        this.pagesModel.description = '';
        this.pagesModel.designation = '';
        this.pagesModel.image = '';
        this.pagesModel.profileimage = '';
        this.testimonialimgRemoved = [];
        this.ticketName = [];
        this.ticketName2 = [];
        this.form.reset({});
        this.form2.reset({});

      },
      () => {
        this.pagesModel.testimonialId = '';
        this.pagesModel.name = '';
        this.pagesModel.description = '';
        this.pagesModel.designation = '';
        this.pagesModel.image = '';
        this.pagesModel.profileimage = '';
        this.testimonialimgRemoved = [];
        this.ticketName = [];
        this.ticketName2 = [];
        this.form.reset({});
        this.form2.reset({});

      }
    );
  }

  addTestimonial(ngForm: any, buttonId) {
    if (ngForm.valid) {
      const formData: any = new FormData();
      formData.append('name', ngForm.value.name);
      formData.append('testimonial_id', ngForm.value.testimonial_id);
      formData.append('description', ngForm.value.description);
      formData.append('designation', ngForm.value.designation);
      for (let i = 0; i < this.ticketName?.length; i++) {
        formData.append('image', this.ticketName[i]);
      }

      const httpOptions = {
        headers: new HttpHeaders({
          Accept: 'application/json',
        }),
      };
      this.sendingResponse[buttonId] = true;

      this.adminService.createTestimonial(formData, httpOptions).subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res.errors) {
            this.toastr.error(this.translate.transform(res.errors.name));
          }
          if (res.success) {
            this.modalService.dismissAll();
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
    }
  }
  editTestimonial(ngForm: any, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      const formData: any = new FormData();
      formData.append('name', ngForm.value.name);
      formData.append('testimonial_id', ngForm.value.testimonial_id);
      formData.append('description', ngForm.value.description);
      formData.append('designation', ngForm.value.designation);

      for (let i = 0; i < this.ticketName2?.length; i++) {
        formData.append('image', this.ticketName2[i]);
      }
      if (this.testimonialimgRemoved) {
        formData.append('testimonialimgRemoved', this.testimonialimgRemoved);
      }

      const httpOptions = {
        headers: new HttpHeaders({
          Accept: 'application/json',
        }),
      };

      this.adminService.createTestimonial(formData, httpOptions).subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res.errors) {
            this.toastr.error(this.translate.transform(res.errors.name));
          }
          if (res.success) {
            this.modalService.dismissAll();
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
    }
  }
  deleteTestimonial(row: any, buttonId) {
    const data = {

      id: row?.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
          .testimonialDelete(row?.id, 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;
            },
          });
      }
    });
  }
  massDeletetestimonials(buttonId) {
    if (!this.selection.selected.length) {
      this.toastr.error(this.translate.transform('Please select atleast one Testimonial'));
      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
          .MassDeletetestimonial(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;
            },
          });
      }
    });
  }

  ticketName: any[] = [];
  ticketName2: any[] = [];
  onImageUploaded(value) {
    this.ticketName = value.ticketName;
  }
  testimonialimgRemoved: any;
  onImageUploaded2(value) {
    this.ticketName2 = value.ticketName;
    if (value.mediaremoveIds) {
      let testimonials = this.testimonials.data.filter(e => e.image == value.mediaremoveIds[0]?.image);
      this.testimonialimgRemoved = testimonials?.[0].id;
    }
  }
  loadData(): Observable<any> {
    this.isloader = true;
    return this.adminService.testimonialSection(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;
  };
}
