import { SelectionModel } from '@angular/cdk/collections';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatPaginatorIntl, PageEvent } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Circulares } from '../../../Administrador/interfaces/Circulares.interface';

import { Router } from '@angular/router';
import { CircularesP } from '../../interfaces/CircularesP.interface';
import { MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import moment from 'moment';
import { CircularService } from '../../../Administrador/services/circular.service';
import { DomSanitizer } from '@angular/platform-browser';
import { EnviarInfoService } from '../../../Administrador/services/enviar-info.service';
import { EventoServiceService } from '../../../Administrador/services/evento-service.service';


@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrl: './main.component.css'
})
export class MainComponent implements OnInit {
  private userData = JSON.parse(localStorage.getItem('userDataS') ? localStorage.getItem('userDataS') || '' : localStorage.getItem('userData') || '');
  public isLoading: boolean = true;
  public event: boolean = true;
  public mensajeBienvenida: string = '';
  public textColor: string = '';
  public message: string = '';

  public result: number = 0;
  public currentDate = new Date();
  public currentYear: any;
  public currentMonth: any;

  public today: any;
  public dias: string[] = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes'];
  public columnasCirculares: string[] = ['titulo', 'publicadaPor', 'estado', 'importancia', 'fechaPublicacion', 'adjuntos', 'acciones'];
  public titulos: string[] = ['Información General - visita', 'Pago de colegiaturas pendientes', 'Descarga Administrativa', 'Visita a Six Flags', 'Visita Educativa', 'Expo-Arte', 'Fotografía de Grupo'];
  public dataSourceCirculares = new MatTableDataSource<CircularesP>();
  public primerColorTitulos: string = '';
  public colorVinculos: string = '';
  public link: string = '';
  public color: string = '';
  public cardsMain = [
    { img: "assets/img/libro.png", texto: "Inscripciones", pendiente: true, url: "main" },
    { img: "assets/img/colegiatura.png", texto: "Colegiaturas", pendiente: true, url: "main" },
    { img: "assets/img/uniforme.png", texto: "Útiles", pendiente: false, url: "main" },
    { img: "assets/img/facturas.png", texto: "Facturas", pendiente: false, url: "main" },
    { img: "assets/img/hijos.png", texto: "Mis hijos", pendiente: true, url: "misHijos" },
  ]
  public weekDays: any[] = [];
  public isLoadingEvents: boolean = false;

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

  constructor(
    private paginator: MatPaginatorIntl,
    private router: Router,
    public dialog: MatDialog,
    public circularService: CircularService,
    private sanitizer: DomSanitizer,
    private _enviarInfo: EnviarInfoService,
    private eventService: EventoServiceService
  ) {

    //paginador de la tabla en 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;

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

  }

  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.weekNumber();
    this.currentMonthYear();
    this.days();
    this.tablaCirculares();
  }

  ngAfterViewInit(): void {

    this.dataSourceCirculares.paginator = this.paginatorCirc;
  }

  navegar(url: string) {
    this.router.navigate([`/homePadres/${url}`])
  }

  //data de la tabla de circulares
  tablaCirculares() {
    return this.circularService.getByUser(this.userData[0]).subscribe((response: any) => {
      this.isLoading = false;
      this.dataSourceCirculares = new MatTableDataSource<any>(response.filter((filtro: any) => filtro.estado === 'Activo'));
      this.dataSourceCirculares.paginator = this.paginatorCirc;

      response.forEach((item: any) => {
        if (typeof item.jsonAdjuntos === 'string') {
          item.jsonAdjuntos = JSON.parse(item.jsonAdjuntos);
        }
        if (!Array.isArray(item.jsonAdjuntos)) {
          item.jsonAdjuntos = [];
        }
      });

      return response;
    });
  }

  buscarArchivo(ruta: string) {
    window.open(ruta, '_blank');
  }

  //traer el número de la semana actual del año
  weekNumber() {
    let currentdate: any = new Date();
    let oneJan: any = new Date(currentdate.getFullYear(), 0, 1);
    let numberOfDays = Math.floor((currentdate - oneJan) / (24 * 60 * 60 * 1000));
    this.result = Math.ceil((currentdate.getDay() + 1 + numberOfDays) / 7);
  }

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

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

  //día actual seleccionado
  selectedDay(dia: string) {
    localStorage.setItem('dia', dia)
  }

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

  //modal circulares
  openDialog(circular: any) {
    this.dialog.open(ModalCircular, {
      data: { titulo: circular.titulo, contenido: this.sanitizer.bypassSecurityTrustHtml(circular.contenido) }
    });
    if (localStorage.getItem('userDataS')) {

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




}

//componente vista de la circular
@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: './circular.component.html',
  styleUrl: './main.component.css'

})
export class ModalCircular {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any,

  ) { }


}
