import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatPaginatorIntl, PageEvent } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Circulares } from '../../interfaces/Circulares.interface';
import { EnviarInfoService } from '../../services/enviar-info.service';
import { ActividadService } from '../../services/actividad.service';
import { MatDialog } from '@angular/material/dialog';
import { UsersService } from '../../services/users.service';
import { CircularService } from '../../services/circular.service';
import { DomSanitizer } from '@angular/platform-browser';
import moment from 'moment';


@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrl: './main.component.css'
})
export class MainComponent implements OnInit {

  public totalUsers: any;
  public teachers: any;
  public students: any;
  public parents: any;
  public event: boolean = true;
  public mensajeBienvenida: string = '';
  public result: number = moment().week();
  public currentDate = new Date();
  public currentYear: any;
  public currentMonth: any;
  public week: { [key: string]: number }[] = [];
  public today: any;
  public message: string = '';
  public color: string = '';
  public textColor: string = '';
  public link: string = '';
  public publicIP: string = '';
  public localIP: string = '';
  public columnasCirculares: string[] = ['titulo', 'receptoresAudiencia', 'importancia', 'fechaPublicacion', 'fechaCaducidad', 'visualizar'];
  public columnasActividades: string[] = ['idUsuario', 'nombre', 'rol', 'horaEntrada', 'horaSalida', 'acciones'];
  public dataSourceCirculares = new MatTableDataSource<Circulares>();
  public dataSourceActividad = new MatTableDataSource();
  public primerColorTitulos: string = '';
  public colorVinculos: string = '';
  public isLoading: boolean = true;
  public weekDays: any[] = [];

  @ViewChild('paginador1') paginatorAct!: MatPaginator;
  @ViewChild('paginador2') paginatorCirc!: MatPaginator;

  constructor(
    private paginator: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    private actividadService: ActividadService,
    private userService: UsersService,
    public dialog: MatDialog,
    private circularService: CircularService,
  ) {
    
    //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.paginator.nextPageLabel = "Siguiente";
    this.paginator.previousPageLabel = "Anterior";
    this.paginator.firstPageLabel = "Ir a la primer página";
    this.paginator.lastPageLabel = "Ir a la última página";
    this.paginator.itemsPerPageLabel = "Registros por página";
    this.paginator.getRangeLabel = spanishRangeLabel;
  }

  ngOnInit() {

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

    this._enviarInfo.currentMensaje.subscribe(message => {
      this.message = message;
    });

    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });
    this._enviarInfo.currentLink.subscribe(link => {
      this.link = link;
    });

    this.currentMonthYear();
    this.days();
    this.circularTable();
    this.activitiesTable();

    setTimeout(() => {
      this.estadisticas()
    }, 1000);

  }

  ngAfterViewInit(): void {
    this.dataSourceActividad.paginator = this.paginatorAct;
    this.dataSourceCirculares.paginator = this.paginatorCirc;
  }

  estadisticas() {
    return this.userService.getStats().subscribe((response: any) => {
      this.isLoading = false;
      this.totalUsers = response.totalUsers;
      this.teachers = response.teachers;
      this.students = response.students;
      this.parents = response.parents;
      // console.log(response);
    });
  }

  //data de tabla circulares
  circularTable() {
    return this.circularService.getUltimas().subscribe((response: any) => {
      this.isLoading = false;
      this.dataSourceCirculares = new MatTableDataSource<any>(response.filter((filtro: any) => filtro.estado === 'Activo'));
      this.dataSourceCirculares.paginator = this.paginatorCirc;
      console.log(response);

      return response;
    })
  }

  //data de tabla actividades
  activitiesTable() {
    return this.actividadService.getAll().subscribe((response: any) => {
      this.dataSourceActividad = new MatTableDataSource(response.data);
      this.dataSourceActividad.paginator = this.paginatorAct;
    })
  }

  //abrir modal
  openDialog(id: any) {
    const dialogRef = this.dialog.open(ModalInfo, {
      autoFocus: false
    });
    dialogRef.componentInstance?.setData(id);
  }

  //abrir modal
  openDialog1(id: any) {
    const dialogRef = this.dialog.open(ModalCircularMain, {
      autoFocus: false
    });
    dialogRef.componentInstance?.setData(id);
  }

  //traer el mes actual
  currentMonthYear() {
    let currentDate = new Date();
    this.currentMonth = currentDate.toLocaleString('default', { month: 'long' });
    this.currentYear = currentDate.getFullYear();
  }

  //cambio de vista en el calendario dependiendo el botón
  calendarView(vista: string) {
    let fecha = moment(new Date).format('YYYY-MM-DD');
    localStorage.setItem('vista', vista);
    localStorage.setItem('dia', fecha);
  }

  //día seleccionado para mostrar en el calendario
  selectedDay(day: string) {
    localStorage.setItem('dia', day)
  }

  //días de la semana actual con eventos
  days() {
    const currentDate = new Date();
    this.today = currentDate.toISOString().split('T')[0];
    const currentDay = currentDate.getDay();

    const days = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes'];
    const events = ['Sin Evento', 'Sin Evento', 'Clase Libre', 'Clase Libre', 'Sin Evento'];
    this.weekDays = [];

    let monday = currentDay - 1;
    if (monday < 0) {
      monday = 6;
    }

    for (let i = 0; i < 5; i++) {
      // const dia = (monday + i) % 7;
      const date = new Date();
      date.setDate(date.getDate() + i - monday);
      const objectDay = {
        day: days[i],
        event: events[i],
        num: date.getDate(),
        completeDate: date.toISOString().split('T')[0]
      };
      this.weekDays.push(objectDay);
    }
  }
}

@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'modalInfo.component.html',
  styleUrl: './main.component.css'

})

export class ModalInfo {
  public isLoading: boolean = true;
  public data: any;
  public widowWidth!: number;
  constructor(public dialog: MatDialog, private actividadService: ActividadService) {
  }

  setData(id: any) {
    this.actividadService.getOne(id).subscribe((response: any) => {
      this.isLoading = false;
      this.data = response.data[0];

    })
  }
}


@Component({
  selector: 'dialog-content-example-dialog-main',
  templateUrl: 'modalCircular.component.html',
  styleUrl: './main.component.css'

})

export class ModalCircularMain {
  public isLoading: boolean = true;
  public data: any;
  public title: string = '';

  constructor(
    public dialog: MatDialog,
    private sanitizer: DomSanitizer,
    private circularService: CircularService
  ) { }

  public circular: any;

  setData(id: any) {
    this.circularService.getOne(id).subscribe((response: any) => {
      console.log(response);
      this.isLoading = false;
      this.title = response.titulo
      this.data = this.sanitizer.bypassSecurityTrustHtml(response.contenido);
    });
  }



}