import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
import { EnviarInfoService } from '../../services/enviar-info.service';
import { CategoriasMateriasService } from '../../services/categorias-materias.service';
import { CategoriaMateria } from '../../interfaces/CategoriasMaterias.interface';
import { MatDialog } from '@angular/material/dialog';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { filter } from 'rxjs';

@Component({
  selector: 'app-categorias-materias',
  templateUrl: './categorias-materias.component.html',
  styleUrl: './categorias-materias.component.css'
})
export class CategoriasMateriasComponent {
  public columnas: string[] = ['nombreCategoria', 'ordenBoleta', 'estado', 'acciones'];
  public allInfo: any;
  public dataSource: any;
  public color: string = '';
  public textColor: string = '';

  @ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator;
  @ViewChild('TABLE') table!: ElementRef;


  constructor(
    private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private paginatorIntl: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    private categoriasMateriasService: CategoriasMateriasService,
    public dialog: MatDialog
  ) {
    this._MatIconRegister.addSvgIcon('excel', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/excel.svg'));
    //paginador de la tabla a español
    const spanishRangeLabel = (page: number, pageSize: number, length: number): string => {
      if (length === 0 || pageSize === 0) {
        return `0 de ${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} de ${length}`;
    };
    this.paginatorIntl.nextPageLabel = "Siguiente";
    this.paginatorIntl.previousPageLabel = "Anterior";
    this.paginatorIntl.firstPageLabel = "Ir a la primer página";
    this.paginatorIntl.lastPageLabel = "Ir a la última página";
    this.paginatorIntl.itemsPerPageLabel = "Registros por página";
    this.paginatorIntl.getRangeLabel = spanishRangeLabel;
  }

  ngOnInit(): void {
    this._enviarInfo.currentTextColor.subscribe(textColor => {
      this.textColor = textColor;
    });
    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });
    this._enviarInfo.tabla$.subscribe(() => {
      this.getCategorias();
    });
    this.getCategorias();
  }

  //filtro de buqueda 
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  getCategorias() {
    this.categoriasMateriasService.getAllCategorias().subscribe(
      (response: any) => {
        this.isLoading = false;
        this.dataSource = new MatTableDataSource<CategoriaMateria>(response.filter((filtro: any) => filtro.estado === 'Activo'));
        this.dataSource.paginator = this.paginator;
        this.allInfo = response
        console.log(response);
      },
      (error: any) => {
        this.isLoading = false;
        console.error('Error fetching categories:', error);
      }
    );
  }

  public isLoading: boolean = true;



  option(event: string) {
    this.isLoading = true;
    if (event === 'Activos') {
      this.dataSource = this.allInfo.filter((filtro: any) => filtro.estado === 'Activo')
    } else if (event === 'Todo') {
      // Muestra todos los registros recargando los datos
      this.dataSource = this.allInfo
    }
    this.isLoading = false;
  }


  //exportar búsqueda a excel
  exportAsExcel() {
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table.nativeElement);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'COLEGIOABC-ConsultaCatMaterias');
    XLSX.writeFile(wb, 'CategoríasMaterias.xlsx');

  }

  //exportar todo a excel
  exportAll() {
    const dataSource = this.dataSource.data;
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(dataSource);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'COLEGIOABC-ConsultaCatMaterias');
    XLSX.writeFile(wb, 'CategoríasMaterias.xlsx');
  }




  deleteCategoria(id: string) {

    Swal.fire({
      icon: 'question',
      title: '¿Desea cambiar el estado del grupo?',
      showCancelButton: true,
      allowEscapeKey: false,
      allowOutsideClick: false,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: "Eliminar",
    }).then((result: any) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        this.categoriasMateriasService.eliminarCategoria(id).subscribe((response: any) => {
          console.log(response);
          Swal.fire({
            icon: 'success',
            title: 'Grupo deshabilitado',
            confirmButtonColor: 'rgb(237,46,56)',
            confirmButtonText: 'Ok',
          }).then((result: any) => {

            if (result.isConfirmed) {
              this.ngOnInit();
              Swal.close();
            }
          })
        }, (err) => {
          console.log(err);
          Swal.fire({
            icon: 'error',
            title: 'Error al eliminar',
            text: `${err.error.mensaje}`,
          })
          this.ngOnInit();
        }
        )
      } else if (result.dismiss == 'cancel') {
        this.ngOnInit();
      }
    });

  }

  enableCategoria(id: string) {
    Swal.fire({
      icon: 'question',
      title: '¿Desea habilitar el grado?',
      showCancelButton: true,
      allowEscapeKey: false,
      allowOutsideClick: false,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: "Habilitar",
    }).then((result: any) => {

      if (result.value) {
        this.categoriasMateriasService.habilitarCategoria(id).subscribe((response: any) => {
          Swal.fire({
            icon: 'success',
            title: 'Grado educativo habilitado',
            confirmButtonColor: 'rgb(237,46,56)',
            confirmButtonText: 'Ok',
          }).then((result: any) => {
            if (result.isConfirmed) {
              Swal.close();
              this.ngOnInit();
            }
          })
        }, (err) => {
          console.log(err);
          Swal.fire({
            icon: 'error',
            title: 'Error al habilitar',
            text: `${err.error.message}`,
          })
        }
        )
      } else if (result.dismiss == 'cancel') {
        this.ngOnInit();
      }
    });
  }

  openDialog(id: string) {
    const dialogRef = this.dialog.open(ModalCategoriasEdit, {
      autoFocus: false
    });

    //esto es para actualizar la tabla una vez actualizada la info
    dialogRef.componentInstance.nivelActualizado.subscribe(() => {
      this.getCategorias();
    });

    dialogRef.componentInstance.setData(id);
  }

}


@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'editar.component.html',
  styleUrl: './categorias-materias.component.css'

})

export class ModalCategoriasEdit implements OnInit {
  public isLoading: boolean = true;
  public data: any;
  public dataNiveles: any;

  public widowWidth!: number;
  //esto es para actualizar la tabla
  @Output() nivelActualizado = new EventEmitter<void>();
  constructor(public dialog: MatDialog, private categoriasMateriasService: CategoriasMateriasService) {
  }

  ngOnInit(): void {

  }

  public form = new FormGroup({
    categoria: new FormControl<string>({ value: '', disabled: true }),
    ordenBoleta: new FormControl<string>('', Validators.required),

  })
  setData(id: any) {
    this.categoriasMateriasService.getOne(id).subscribe((response: any) => {
      console.log(response);
      this.isLoading = false;
      this.data = response;

      // mostrar data en el formulario
      this.form.controls['categoria'].setValue(this.data.categoria);
      this.form.controls['ordenBoleta'].setValue(this.data.ordenBoleta);

    }, (err) => {
      console.log(err);
    })
  }

  editarCategoria() {

    let info = {
      id: this.data.categoria,
      categoria: this.data.categoria,
      ordenBoleta: this.form.value.ordenBoleta,
    }


    this.categoriasMateriasService.actualizarCategoria(info).subscribe((response: any) => {
      console.log(response);
      Swal.fire({
        icon: 'success',
        title: `${response.mensaje}`
      })
      this.dialog.closeAll();
      this.nivelActualizado.emit();
    }, (err) => {
      console.log(err);
      Swal.fire({
        icon: 'error',
        title: `${err.message}`
      })
    })
  }

  close() {
    this.dialog.closeAll()
  }

  limpiar() {
    this.form.reset();
  }

  campoNoValido(campo: string): boolean {
    if (this.form.get(campo)?.invalid && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }

  campoVacio(campo: string): boolean {
    if ((this.form.get(campo)?.value === '') && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }
}