import { Component, ElementRef, Inject, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { CircularService } from '../../../Administrador/services/circular.service';
import { MatIconModule, MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { EnviarInfoService } from '../../../Administrador/services/enviar-info.service';
import { MAT_DIALOG_DATA, MatDialog, MatDialogActions, MatDialogClose, MatDialogContent } from '@angular/material/dialog';
import { ModalTarea } from '../../../Profesor/pages/tareas/tareas.component';

import * as XLSX from 'xlsx';
import { TareasService } from '../../services/tareas.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-tareas',
  templateUrl: './tareas-hijos.component.html',
  styleUrl: './tareas-hijos.component.css'
})
export class TareasHijosComponent {
  public checked = false;
  public isLoading: boolean = true;
  public searchInput = new FormControl('');
  public color: string = '';
  public textColor: string = '';
  public columnas: string[] = ['titulo', 'materia', 'tipoTarea', 'fechaPub', 'fechaEntrega', 'enlaces', 'adjuntos', 'acciones'];
  public dataSource = new MatTableDataSource<any>();
  private userData = JSON.parse(localStorage.getItem('userData') || '[]');
  private userDataS = JSON.parse(localStorage.getItem('userDataS') || '[]');
  @ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator;
  @ViewChild('TABLE') table!: ElementRef;

  constructor(
    private circularService: CircularService,
    private sanitizer: DomSanitizer,
    private tareasService: TareasService,
    private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private paginatorIntl: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    public dialog: MatDialog,
    private route: ActivatedRoute
  ) {
    this._MatIconRegister.addSvgIcon('excel', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/excel.svg'));
    //paginador de 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;
  }
  private id: string = '';
  ngOnInit(): void {

    this.route.paramMap.subscribe((params: any) => {
      const id = params.get('id');

      this.id = atob(id || '');
      console.log(this.id);
    });

    this._enviarInfo.currentTextColor.subscribe(textColor => {
      this.textColor = textColor;
    });
    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });

    //suscribirse al subject que manda al servicio
    this._enviarInfo.tabla$.subscribe(() => {
      this.getCirculares();
    });

    this.getCirculares()

  }

  openDialog(circular: any) {
    this.dialog.open(TareaAlumComponent, {
      data: { titulo: circular.tituloTarea, contenido: this.sanitizer.bypassSecurityTrustHtml(circular.descripcionTarea) }
    });

    if (localStorage.getItem('userDataS')) {

    } else {
      let info = {
        idCircular: circular.idCircular,
        idUsuario: this.userData[0]
      };
      this.circularService.verCircular(info).subscribe((response) => {
      });
    }
  }



  public allInfo: any;
  public files: any;
  public urls: any = [];
  //Traer la información y mostrarla en la tabla
  getCirculares() {
    this.tareasService.getTareas(this.id).subscribe((response: any) => {
      this.isLoading = false;

      this.allInfo = response.map((tarea: any) => {
        // separar los vinculos en un arreglo de objetos con nombre
        if (tarea.vinculoTarea) {
          tarea.vinculoTareaArray = tarea.vinculoTarea.split("||").map((url: string, index: number) => {
            return { nombre: url, url: url };
          });
        } else {
          tarea.vinculoTareaArray = [];
        }

        if (tarea.adjuntoTarea) {
          tarea.adjuntoTarea = JSON.parse(tarea.adjuntoTarea);
        } else {
          tarea.adjuntoTarea = [];
        }

        return tarea;
      });


      this.dataSource = new MatTableDataSource<any>(this.allInfo);
      this.dataSource.paginator = this.paginator;
    });
  }

  buscarArchivo(ruta: string) {
    // console.log("🚀 ~ TareasComponent ~ buscarArchivo ~ ruta:", ruta)
    window.open(ruta, '_blank');
  }

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




  // openDialog1(id: string) {
  //   const dialogRef = this.dialog.open(ModalCircular, {
  //     autoFocus: false
  //   });


  //   dialogRef.componentInstance.setData(id);
  // }



  // openDialogEdit(circular: any) {
  //   console.log("🚀 ~ CircularesComponent ~ openDialogEdit ~ circular:", circular)
  //   const dialogRef = this.dialog.open(ModalCircularesEdit, {
  //     autoFocus: false,
  //     data: circular
  //   });

  //   dialogRef.componentInstance.circularActualizada.subscribe(() => {
  //     this.getCirculares();
  //   });


  // }




}

@Component({
  selector: 'App-circularAlumno-component',
  templateUrl: './tareaAlumno.component.html',
  styleUrls: ['./tareas-hijos.component.css'],
  standalone: true,
  imports: [MatIconModule, MatDialogContent, MatDialogActions, MatDialogClose]
})
export class TareaAlumComponent {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) {
  }
}