import { Component, OnDestroy, OnInit } from '@angular/core';
import { CalendarOptions } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import timeGridPlugin from '@fullcalendar/timegrid'
import listPlugin from '@fullcalendar/list';
import { CalendarService } from '../../services/calendar.service';
import { MatDialog } from '@angular/material/dialog';
import { provideNativeDateAdapter } from '@angular/material/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Editor, Toolbar } from 'ngx-editor';
import { forkJoin } from 'rxjs';
import { NivelEducativoService } from '../../services/nivel-educativo.service';
import { GradosEducativosService } from '../../services/grados-educativos.service';
import { GruposService } from '../../services/grupos.service';
import { MateriaService } from '../../services/materia.service';




@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrl: './calendar.component.css'
})
export class CalendarComponent implements OnInit {
  public valor: string = localStorage.getItem('vista') || '';
  public fecha: string = localStorage.getItem('dia') || '';
  public primerColorTitulos: string = '';
  public eventList: any;

  constructor(private calendarService: CalendarService, public dialog: MatDialog) { }

  ngOnInit() {
    let primerColorTitulos = localStorage.getItem('primerColorTitulos') || ''
    this.primerColorTitulos = primerColorTitulos;
    this.getEvents();
  }

  sumarDias(fecha: Date, dias: number) {
    fecha.setDate(fecha.getDate() + dias);
    return fecha;
  }

  getEvents() {
    this.calendarService.allEvents().subscribe((response: any) => {
      const events = response.map((event: any) => ({
        id: event.id,
        title: event.title,
        start: this.sumarDias(new Date(event.start), 1).toISOString(),
        end: this.sumarDias(new Date(event.end), 1).toISOString(),

        // start: new Date(event.start),
        // end: new Date(event.end),
        description: event.description,
        backgroundColor: event.color
      }));
      this.calendarOptions.events = events;
      // console.log(this.calendarOptions.events);
    });
  }


  calendarOptions: CalendarOptions = {
    // windowResize: function (arg) {
    //   alert('The calendar has adjusted to a window resize. Current view: ' + arg.view.type);
    // },
    initialDate: this.fecha,
    locale: 'es',
    weekNumbers: true,
    weekText: '',
    buttonText: {
      today: 'Hoy',
      timeGridWeek: 'Semana',
      dayGridMonth: 'Mes',
      listWeek: 'Agenda',
      dayGridDay: 'Día'
    },
    headerToolbar: {

      start: 'today prev,next',
      center: 'title',
      end: 'dayGridMonth,timeGridWeek,dayGridDay,listWeek',
    },
    initialView: this.valor,
    navLinks: true,
    editable: true,
    selectable: true,
    selectMirror: true,
    dayMaxEvents: true,
    plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin, listPlugin],
    // dateClick: (arg) => this.handleDateClick(arg),
    events: [
      // {
      //   id: 'a',
      //   title: 'my event',
      //   start: '2024-06-01'
      // }
    ]

  };

  // handleDateClick(arg: any) {
  //   prompt('date click! ' + arg.dateStr)
  // }

  openDialog() {
    this.dialog.open(ModalEvent, {
      autoFocus: false
    });
  }
};

@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'modalEvent.component.html',
  styleUrl: './calendar.component.css',
  providers: [provideNativeDateAdapter()],
})

export class ModalEvent implements OnInit, OnDestroy {
  editor!: Editor;
  toolbar: Toolbar = [
    ['bold', 'italic'],
    ['underline', 'strike'],
    ['code', 'blockquote'],
    ['ordered_list', 'bullet_list'],
    [{ heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }],
    ['link', 'image'],
    ['text_color', 'background_color'],
    ['align_left', 'align_center', 'align_right', 'align_justify'],
  ];
  colorPresets = [
    "#000000", // Negro
    "#FF0000", // Rojo
    "#00FF00", // Verde
    "#0000FF", // Azul
    "#FFFF00", // Amarillo
    "#FF00FF", // Magenta
    "#00FFFF", // Cian
    "#808080", // Gris
    "#FFFFFF", // Blanco
    "#800000", // Marrón
    "#008000", // Verde oscuro
    "#000080", // Azul oscuro
    "#808000", // Oliva
    "#800080", // Púrpura
    "#008080", // Verde azulado
    "#C0C0C0"  // Plata

  ];


  ngOnInit(): void {
    this.editor = new Editor();
  }

  ngOnDestroy(): void {
    this.editor.destroy();
  }

  public horasDelDia: any = this.generarHorasDelDia();
  public catEventos = [
    { value: '#6BD716', text: 'Cumpleaños' },
    { value: '#f50f39', text: 'Exámenes' },
    { value: '#F50F9E', text: 'Talleres' },
    { value: '#F5890F', text: 'Académico' },

  ]
  // public hoy = new Date();
  constructor(public dialog: MatDialog,
    private nivelService: NivelEducativoService,
    private gradoService: GradosEducativosService,
    private grupoService: GruposService,
    private materiaService: MateriaService,
  ) {
    // console.log(this.horasDelDia);
    this.lista();
  }

  public form = new FormGroup({
    titulo: new FormControl<string>('', Validators.required),
    fechaInicio: new FormControl<string>('', Validators.required),
    horaInicio: new FormControl<string>('', Validators.required),
    fechaFinal: new FormControl<string>(''),
    horaFinal: new FormControl<string>(''),
    todoDia: new FormControl<boolean>(false),
    categoria: new FormControl<string>(''),
    contenido: new FormControl<string>(''),
    destinos: new FormControl<string>(''),
    audiencia: new FormControl<string>(''),
  })

  public opciones: any[] = [];
  audiencia = [
    { value: 'AL', audiencia: 'Alumnos' },
    { value: 'PF', audiencia: 'Padre de Familia' },
    { value: 'AD', audiencia: 'Administradores' },
    { value: 'PR', audiencia: 'Profesores' },
  ]
  lista() {
    forkJoin({
      niveles: this.nivelService.getHabilitados(),
      grados: this.gradoService.getHabilitados(),
      grupos: this.grupoService.getHabilitados(),
      materias: this.materiaService.getHabilitados(),
    }).subscribe(({ niveles, grados, grupos, materias }: any) => {
      this.opciones = [
        {
          name: 'Nivel Educativo',
          grupo: niveles.map((nivel: any) => ({
            value: nivel.idNivel,
            viewValue: nivel.nombreNivel,
          })),
        },
        {
          name: 'Grados',
          grupo: grados.map((grado: any) => ({
            value: grado.nombreGrado,
            viewValue: grado.nombreGrado,
          })),
        },
        {
          name: 'Grupos',
          grupo: grupos.map((grupo: any) => ({
            value: grupo.idGrupo,
            viewValue: grupo.nombreGrupo,
          })),
        },
        {
          name: 'Materia',
          grupo: materias.map((materia: any) => ({
            value: materia.idMateria,
            viewValue: materia.nombreMateria,
          })),
        },
      ];

      console.log(this.opciones);
    });
  }


  crearEvento() {
    console.log(this.form.value);
  }

  generarHorasDelDia(): { hora24: string, hora12: string }[] {
    const horas: { hora24: string, hora12: string }[] = [];
    let hora: number = 0;
    let minutos: number = 0;

    for (let i = 0; i < 48; i++) {
      let ampm = 'am';
      let hora12: number = hora;

      if (hora === 0) {
        hora12 = 12;
      } else if (hora === 12) {
        ampm = 'pm';
      } else if (hora > 12) {
        hora12 = hora - 12;
        ampm = 'pm';
      }

      const horaFormateada24 = `${hora.toString().padStart(2, '0')}:${minutos.toString().padStart(2, '0')}:00`;
      const horaFormateada12 = `${hora12.toString().padStart(2, '0')}:${minutos.toString().padStart(2, '0')} ${ampm}`;

      horas.push({ hora24: horaFormateada24, hora12: horaFormateada12 });

      minutos += 30;
      if (minutos === 60) {
        minutos = 0;
        hora++;
      }
    }

    return horas;
  }






}
