import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatPaginatorIntl } 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';
import { EventoServiceService } from '../../services/evento-service.service';


@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[] = [];
  public isLoadingEvents: boolean = false;

  @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,
    private eventService: EventoServiceService
  ) {

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

  //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;
      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() {
    this.isLoadingEvents = true;
    const currentDate = new Date();
    this.today = currentDate.toISOString().split('T')[0];
    return this.eventService.getWeekEvents().subscribe(
      (response: any) => {
        console.log(response);
        this.isLoadingEvents = false;
        this.weekDays = response;
      },
      (error) => {
        this.isLoadingEvents = false;
        console.log('Error al obtener eventos:', error);
        // Cargar datos por defecto en caso de error
        this.loadDefaultWeekData();

      }
    )
  }

  private loadDefaultWeekData() {
    const currentDate = new Date();
    const currentDay = currentDate.getDay();
    const days = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes'];

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

    this.weekDays = [];

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

@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 = '';
  public adjuntos: any[] = [];
  public urls: any;

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

  public circular: any;

  // '.xlsx', '.docx', '.pdf', '.pptx', '.txt', '.jpg', '.jpeg', '.png'

  setData(id: any) {
    this.circularService.getOne(id).subscribe((response: any) => {
      console.log(response);
      this.isLoading = false;
      this.title = response.titulo
      this.adjuntos = JSON.parse(response.jsonAdjuntos);
      this.adjuntos.forEach((file:any) => {
        const fileExtension = file.nombre.split('.').pop().toLowerCase();
        switch (fileExtension) {
          case 'pdf':
            file.urlImage = 'https://www.iconpacks.net/icons/2/free-pdf-icon-1512-thumb.png';
            break;
          case 'docx':
          case 'doc':
            file.urlImage = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/.docx_icon.svg/2048px-.docx_icon.svg.png'; // Puedes usar otro icono si lo prefieres
            break;
          case 'xlsx':
          case 'xls':
            file.urlImage = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/.xlsx_icon.svg/2048px-.xlsx_icon.svg.png'; // Puedes usar otro icono si lo prefieres
            break;
          case 'pptx':
          case 'ppt':
            file.urlImage = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/.pptx_icon_%282019%29.svg/2048px-.pptx_icon_%282019%29.svg.png'; // Puedes usar otro icono si lo prefieres
            break;
          case 'txt':
            file.urlImage = 'https://cdn-icons-png.freepik.com/512/8243/8243060.png';
            break;
          case 'jpg':
          case 'jpeg':
            file.urlImage = 'https://cdn-icons-png.flaticon.com/512/136/136524.png';
            break;
          case 'png':
            file.urlImage = 'https://cdn-icons-png.flaticon.com/512/337/337948.png';
            break;
          default:
            file.urlImage = 'https://www.shareicon.net/data/2015/08/11/83725_file_256x256.png'; // Icono genérico para otros tipos de archivo
        }
        
      });
      this.urls = response.urls ? response.urls.split("||") : [];
      console.log(this.urls);
      this.data = this.sanitizer.bypassSecurityTrustHtml(response.contenido);
    });
  }

}
