var start_date = document.getElementById('fecha_horario'),
hora_inicio = document.getElementById('hora_inicio'),
hora_finalizacion = document.getElementById('hora_finalizacion'),
date_range = null,
T_check = null;
function flatPickrInit() {
    var start_date = document.getElementById('fecha_horario'),
        hora_inicio = document.getElementById('hora_inicio'),
        hora_finalizacion = document.getElementById('hora_finalizacion');

    if (start_date) {
        flatpickr(start_date, {
            enableTime: false,
            dateFormat: 'Y-m-d',
            mode: 'range',
            minDate: 'today',
            onChange: function (e, t, n) {
                if (t.split('to').length > 1) {
                    document.getElementById('event-time').setAttribute('hidden', true);
                } else {
                    document.getElementById('hora_inicio').parentNode.classList.remove('d-none');
                    document.getElementById('hora_inicio').classList.replace('d-none', 'd-block');
                    document.getElementById('hora_finalizacion').parentNode.classList.remove('d-none');
                    document.getElementById('hora_finalizacion').classList.replace('d-none', 'd-block');
                    document.getElementById('event-time').removeAttribute('hidden');
                }
            }
        });
    }

    if (hora_inicio) {
        flatpickr(hora_inicio, {
            enableTime: true,
            noCalendar: true
        });
    }

    if (hora_finalizacion) {
        flatpickr(hora_finalizacion, {
            enableTime: true,
            noCalendar: true
        });
    }
}

function flatpicekrValueClear() {
  start_date.flatpickr().clear(),
  hora_inicio.flatpickr().clear(),
  hora_finalizacion.flatpickr().clear()
}
function eventClicked() {
  document.getElementById('form-event').classList.add('view-event'),
  document.getElementById('codigo_horario').classList.replace('d-block', 'd-none'),
  document.getElementById('lista_horarios').classList.replace('d-block', 'd-none'),
  document.getElementById('fecha_horario').parentNode.classList.add('d-none'),
  document.getElementById('fecha_horario').classList.replace('d-block', 'd-none'),
  document.getElementById('event-time').setAttribute('hidden', !0),
  document.getElementById('hora_inicio').parentNode.classList.add('d-none'),
  document.getElementById('hora_inicio').classList.replace('d-block', 'd-none'),
  document.getElementById('hora_finalizacion').parentNode.classList.add('d-none'),
  document.getElementById('hora_finalizacion').classList.replace('d-block', 'd-none'),
  document.getElementById('grupo_trabajo').classList.replace('d-block', 'd-none'),
  document.getElementById('motivo_cambio').classList.replace('d-block', 'd-none'),
  document.getElementById('event-start-date-tag').classList.replace('d-none', 'd-block'),
  document.getElementById('event-timepicker1-tag').classList.replace('d-none', 'd-block'),
  document.getElementById('event-timepicker2-tag').classList.replace('d-none', 'd-block'),
  document.getElementById('event-grupo-trabajo-tag').classList.replace('d-none', 'd-block'),
  document.getElementById('event-jefe-grupo-trabajo-tag').classList.replace('d-none', 'd-block'),
  document.getElementById('btn-save-event').setAttribute('hidden', !0)
}

function editEvent(e) {
  var t = e.getAttribute('data-id');
  (
    'new-event' == t ? (
      document.getElementById('modal-title').innerHTML = '',
      document.getElementById('modal-title').innerHTML = 'Add Event',
      document.getElementById('btn-save-event').innerHTML = 'Add Event',
      eventTyped
    ) : 'edit-event' == t ? (
      e.innerHTML = 'Cancel',
      e.setAttribute('data-id', 'cancel-event'),
      document.getElementById('btn-save-event').innerHTML = 'Update Event',
      e.removeAttribute('hidden'),
      eventTyped
    ) : (
      e.innerHTML = 'Edit',
      e.setAttribute('data-id', 'edit-event'),
      eventClicked
    )
  ) ()
}

function eventTyped() {
  document.getElementById('form-event').classList.remove('view-event'),
  document.getElementById('codigo_horario').classList.replace('d-none', 'd-block'),
  document.getElementById('lista_horarios').classList.replace('d-none', 'd-block'),
  document.getElementById('fecha_horario').parentNode.classList.remove('d-none'),
  document.getElementById('fecha_horario').classList.replace('d-none', 'd-block'), //fecha_horario event-start-date
  document.getElementById('hora_inicio').parentNode.classList.remove('d-none'),
  document.getElementById('hora_inicio').classList.replace('d-none', 'd-block'),
  document.getElementById('hora_finalizacion').parentNode.classList.remove('d-none'),
  document.getElementById('hora_finalizacion').classList.replace('d-none', 'd-block'),
  document.getElementById('grupo_trabajo').classList.replace('d-none', 'd-block'),
  document.getElementById('motivo_cambio').classList.replace('d-none', 'd-block'),
  document.getElementById('event-start-date-tag').classList.replace('d-block', 'd-none'),
  document.getElementById('event-timepicker1-tag').classList.replace('d-block', 'd-none'),
  document.getElementById('event-timepicker2-tag').classList.replace('d-block', 'd-none'),
  document.getElementById('event-grupo-trabajo-tag').classList.replace('d-block', 'd-none'),
  document.getElementById('event-jefe-grupo-trabajo-tag').classList.replace('d-block', 'd-none'),
  document.getElementById('btn-save-event').removeAttribute('hidden')
}
function upcomingEvent(e) {
  e.sort(function (e, t) {
    return new Date(e.start) - new Date(t.start)
  }),
  document.getElementById('upcoming-event-list').innerHTML = null,
  Array.from(e).forEach(
    function (e) {
      var t = e.title,
      n = (
        l = e.end ? (endUpdatedDay = new Date(e.end)).setDate(endUpdatedDay.getDate() - 1) : l
      ) ||
      void 0;
      n = 'Invalid Date' == n ||
      null == n ? null : (
        a = new Date(n).toLocaleDateString('en', {
          year: 'numeric',
          month: 'numeric',
          day: 'numeric'
        }),
        new Date(a).toLocaleDateString('en-GB', {
          day: 'numeric',
          month: 'short',
          year: 'numeric'
        }).split(' ').join(' ')
      );
      (e.start ? str_dt(e.start) : null) === (l ? str_dt(l) : null) &&
      (n = null);
      var a = e.start,
      d = (
        a = 'Invalid Date' === a ||
        void 0 === a ? null : (
          d = new Date(a).toLocaleDateString('en', {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric'
          }),
          new Date(d).toLocaleDateString('en-GB', {
            day: 'numeric',
            month: 'short',
            year: 'numeric'
          }).split(' ').join(' ')
        ),
        n ? ' to ' + n : ''
      ),
      n = e.className.split('-'),
      i = e.description ||
      '',
      e = tConvert(getTime(e.start)),
      l = (
        e == (l = tConvert(getTime(l))) &&
        (e = 'Full day event', l = null),
        l ? ' to ' + l : ''
      );
      u_event = '<div class=\'card mb-3\'>                        <div class=\'card-body\'>                            <div class=\'d-flex mb-3\'>                                <div class=\'flex-grow-1\'><i class=\'mdi mdi-checkbox-blank-circle me-2 text-' + n[1] + '\'></i><span class=\'fw-medium\'>' + a + d + ' </span></div>                                <div class=\'flex-shrink-0\'><small class=\'badge bg-primary-subtle text-primary ms-auto\'>' + e + l + '</small></div>                            </div>                            <h6 class=\'card-title fs-16\'> ' + t + '</h6>                            <p class=\'text-muted text-truncate-two-lines mb-0\'> ' + i + '</p>                        </div>                    </div>',
      document.getElementById('upcoming-event-list').innerHTML += u_event
    }
  )
}
function getTime(e) {
  if (null != (e = new Date(e)).getHours()) return e.getHours() + ':' + (e.getMinutes() ? e.getMinutes() : 0)
}
function tConvert(e) {
  var e = e.split(':'),
  t = e[0],
  e = e[1],
  n = 12 <= t ? 'PM' : 'AM';
  return (t = (t %= 12) || 12) + ':' + (e < 10 ? '0' + e : e) + ' ' + n
}
document.addEventListener(
  'DOMContentLoaded',
  function () {
    flatPickrInit();
    var g = new bootstrap.Modal(document.getElementById('event-modal'), {
      keyboard: !1
    }),
    i = (
      document.getElementById('event-modal'),
      document.getElementById('modal-title')
    ),
    l = document.getElementById('form-event'),
    v = null,
    p = document.getElementsByClassName('needs-validation'),
    e = new Date,
    t = e.getDate(),
    n = e.getMonth(),
    e = e.getFullYear(),
    // a = FullCalendar.Draggable,
    d = document.getElementById('external-events'),
    y = [
      {
        id: 1,
        title: 'World Braille Day',
        start: '2022-01-04',
        className: 'bg-info-subtle',
        allDay: !0
      },
      {
        id: 2,
        title: 'World Leprosy Day',
        start: '2022-01-30',
        className: 'bg-info-subtle',
        allDay: !0
      },
    ],
    e = (
    //   new a(
    //     d,
    //     {
        //   itemSelector: '.external-event',
        //   eventData: function (e) {
        //     return {
        //       id: Math.floor(11000 * Math.random()),
        //       title: e.innerText,
        //       allDay: !0,
        //       start: new Date,
        //       className: e.getAttribute('data-class')
        //     }
        //   }
    //     }
    //   ),
      document.getElementById('calendar')
    );
    function o(e) {
      document.getElementById('form-event').reset(),
      document.getElementById('btn-delete-event').setAttribute('hidden', !0),
      g.show(),
      l.classList.remove('was-validated'),
      l.reset(),
      v = null,
      i.innerText = 'Add Event',
      newEventData = e,
      document.getElementById('edit-event-btn').setAttribute('data-id', 'new-event'),
      document.getElementById('edit-event-btn').click(),
      document.getElementById('edit-event-btn').setAttribute('hidden', !0)
    }
    function r() {
      return 768 <= window.innerWidth &&
      window.innerWidth < 1200 ? 'timeGridWeek' : window.innerWidth <= 768 ? 'listMonth' : 'dayGridMonth'
    }
    var c = new Choices('#lista_horarios', {
      searchEnabled: !1
    });
    var b = new FullCalendar.Calendar(e, {
    timeZone: "local",
    editable: true,
    droppable: true,
    selectable: true,
    navLinks: true,
    initialView: r(),
    themeSystem: "bootstrap",
    headerToolbar: {
        left: "prev,next today",
        center: "title",
        right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth"
    },
    windowResize: function(e) {
        var t = r();
        b.changeView(t);
    },
    eventResize: function(t) {
        var eventIndex = y.findIndex(function(e) {
            return e.id == t.event.id;
        });
        if (y[eventIndex]) {
            y[eventIndex].title = t.event.title;
            y[eventIndex].start = t.event.start;
            y[eventIndex].end = t.event.end || null;
            y[eventIndex].allDay = t.event.allDay;
            y[eventIndex].className = t.event.classNames[0];
            y[eventIndex].description = t.event._def.extendedProps.description || "";
            y[eventIndex].location = t.event._def.extendedProps.location || "";
            upcomingEvent(y);
        }
    },
    eventClick: function(e) {
        document.getElementById("edit-event-btn").removeAttribute("hidden");
        document.getElementById("btn-save-event").setAttribute("hidden", true);
        document.getElementById("edit-event-btn").setAttribute("data-id", "edit-event");
        document.getElementById("edit-event-btn").innerHTML = "Edit";
        eventClicked(); // Lógica de edición del evento
        flatPickrInit();
        flatpicekrValueClear();
        g.show();
        l.reset();
        v = e.event;
        
        document.getElementById("btn-delete-event").removeAttribute("hidden");
        // Aquí se configura el modal con los valores del evento
        configurarModalConEvento(v);
        // No crear nuevo evento, solo actualizar el existente
        newEventData = null;
        
    },
    dateClick: function(e) {
        o(e); // Lógica cuando se hace click en una fecha vacía
    },
    events: y,
    eventReceive: function(e) {
        
        // var existingEvent = calendar.getEventById(info.event.id);
        // if (existingEvent) {
        // console.log('Evento ya existe, no se agregará de nuevo');
        // info.event.remove(); // Remover el evento duplicado
        // } else {
        //     console.log('Evento agregado');
        //     // Lógica para agregar el evento si no existe
        // }
    
        // Verifica si el evento ya existe antes de agregarlo
        // var existingEvent = y.find(function(evt) {
        //     return evt.id === e.event.id;
        // });
        // if (!existingEvent) {
        //     // Si no existe, entonces se agrega
        //     var newEvent = {
        //         id: parseInt(e.event.id),
        //         title: e.event.title,
        //         start: e.event.start,
        //         allDay: e.event.allDay,
        //         className: e.event.classNames[0]
        //     };
        //     y.push(newEvent);
        //     upcomingEvent(y);
        // } else {
        //     // Si el evento ya existe, evitar duplicados
        //     e.event.remove();
        // }
    },
    eventDrop: function(t) {
        var eventIndex = y.findIndex(function(e) {
            return e.id == t.event.id;
        });
        if (y[eventIndex]) {
            y[eventIndex].title = t.event.title;
            y[eventIndex].start = t.event.start;
            y[eventIndex].end = t.event.end || null;
            y[eventIndex].allDay = t.event.allDay;
            y[eventIndex].className = t.event.classNames[0];
            y[eventIndex].description = t.event._def.extendedProps.description || "";
            y[eventIndex].location = t.event._def.extendedProps.location || "";
            upcomingEvent(y);
        }
    }
});
  b.render();
upcomingEvent(y);

l.addEventListener('submit', function (e) {
  e.preventDefault();

  var t,
    n,
    e = document.getElementById('codigo_horario').value,
    a = document.getElementById('lista_horarios').value,
    d = document.getElementById('fecha_horario').value.split('to'),
    i = new Date(d[0].trim()),
    l = new Date(d[1]),
    l = (l.setDate(l.getDate() + 1), d[1] ? l : ''),
    o = null,
    r = document.getElementById('grupo_trabajo').value,
    c = document.getElementById('motivo_cambio').value,
    s = document.getElementById('eventid').value,
    m = !1,
    u = (
      1 < d.length ? (
        (o = new Date(d[1])).setDate(o.getDate() + 1),
        d = new Date(d[0]),
        m = !0
      ) : (
        t = d,
        u = document.getElementById('hora_inicio').value.trim(),
        n = document.getElementById('hora_finalizacion').value.trim(),
        // d = new Date(d + 'T' + u),
        o = new Date(t + 'T' + n)
      ),
      y.length + 1
    );

  if (!p[0].checkValidity()) {
    p[0].classList.add('was-validated');
  } else {
    // Verificar si ya existe un evento con el mismo ID
    var existingEvent = b.getEventById(s);
    
    if (existingEvent) {
      // Si el evento existe, lo actualizamos
      existingEvent.setProp('title', e);
      existingEvent.setProp('classNames', [a]);
      existingEvent.setStart(i);
      existingEvent.setEnd(l);
      existingEvent.setAllDay(m);
      existingEvent.setExtendedProp('description', c);
      existingEvent.setExtendedProp('location', r);
    } else {
      // Si el evento no existe, lo agregamos
      var newEvent = {
        id: u,
        title: e,
        start: d,
        end: o,
        allDay: m,
        className: a,
        description: c,
        location: r
      };
      b.addEvent(newEvent);
      y.push(newEvent);
    }

    b.render();
    g.hide();
    upcomingEvent(y);
  }
});

// document.getElementById('btn-delete-event').addEventListener('click', function (e) { console.log(v);
//   if (v) {
//     for (var t = 0; t < y.length; t++) {
//       if (y[t].id == v.id) {
//         y.splice(t, 1);
//         t--;
//       }
//     }
//     upcomingEvent(y);
//     v.remove();
//     v = null;
//     g.hide();
//   }
// });

document.getElementById('btn-new-event').addEventListener('click', function (e) {
  flatpicekrValueClear();
  flatPickrInit();
  o();
  document.getElementById('edit-event-btn').setAttribute('data-id', 'new-event');
  document.getElementById('edit-event-btn').click();
  document.getElementById('edit-event-btn').setAttribute('hidden', !0);
});


})
var str_dt = function (e) {
  var e = new Date(e),
  t = '' + ['January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'][e.getMonth()],
  n = '' + e.getDate(),
  e = e.getFullYear();
  return t.length < 2 &&
  (t = '0' + t),
  [
    (n = n.length < 2 ? '0' + n : n) + ' ' + t,
    e
  ].join(',')
};