/**
 * Team Leave Calendar
 */

'use strict';

import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';

document.addEventListener('DOMContentLoaded', function() {
  // Get calendar data from window
  const calendarData = window.teamCalendarData || { leaves: [], leaveTypes: [] };
  const labels = window.pageData?.labels || {};
  
  // Initialize calendar
  const calendarEl = document.getElementById('teamCalendar');
  
  if (calendarEl) {
    const calendar = new Calendar(calendarEl, {
      plugins: [dayGridPlugin, interactionPlugin],
      initialView: 'dayGridMonth',
      headerToolbar: false, // We're using custom navigation
      height: 'auto',
      editable: false,
      selectable: false,
      events: calendarData.leaves,
      eventDisplay: 'block',
      displayEventTime: false,
      eventDidMount: function(info) {
        // Add tooltip with leave details
        info.el.setAttribute('data-bs-toggle', 'tooltip');
        info.el.setAttribute('data-bs-placement', 'top');
        info.el.setAttribute('data-bs-html', 'true');
        
        const event = info.event;
        const statusLabel = event.extendedProps.status === 'approved' ? (labels.approved || 'Approved') : (labels.pending || 'Pending');
        const tooltipContent = `
          <div class="text-start">
            <strong>${event.extendedProps.user}</strong><br>
            <small>${event.extendedProps.leaveType}</small><br>
            <small>${event.extendedProps.totalDays} ${labels.days || 'day(s)'}</small>
            ${event.extendedProps.isHalfDay ? '<br><small>' + (labels.halfDay || 'Half Day') + ' (' + event.extendedProps.halfDayType + ')</small>' : ''}
            <br><span class="badge bg-label-${event.extendedProps.status === 'approved' ? 'success' : 'warning'}">${statusLabel}</span>
          </div>
        `;
        info.el.setAttribute('title', tooltipContent);
        
        // Initialize tooltip
        new bootstrap.Tooltip(info.el);
        
        // Add status class
        info.el.classList.add('leave-status-' + event.extendedProps.status);
      },
      eventClick: function(info) {
        // Show leave details modal
        showLeaveDetails(info.event);
      },
      dayCellDidMount: function(info) {
        // Highlight today
        if (info.isToday) {
          info.el.classList.add('fc-day-today');
        }
        
        // Highlight weekends
        if (info.date.getDay() === 0 || info.date.getDay() === 6) {
          info.el.classList.add('fc-day-weekend');
        }
      }
    });
    
    calendar.render();

    // Update month/year display on initial render
    updateCalendarTitle();

    // Custom navigation buttons
    document.getElementById('calendarPrev')?.addEventListener('click', () => {
      calendar.prev();
      updateCalendarTitle();
    });

    document.getElementById('calendarNext')?.addEventListener('click', () => {
      calendar.next();
      updateCalendarTitle();
    });

    document.getElementById('calendarToday')?.addEventListener('click', () => {
      calendar.today();
      updateCalendarTitle();
    });

    // Update calendar title
    function updateCalendarTitle() {
      const title = calendar.view.title;
      const titleEl = document.getElementById('calendarMonthYear');
      if (titleEl) {
        titleEl.textContent = title;
      }
    }
    
    // Initialize Select2
    if ($('.select2').length) {
      $('#designationFilter').select2({
        placeholder: labels.allDesignations || 'All Designations',
        allowClear: true
      });

      $('#leaveTypeFilter').select2({
        placeholder: labels.allLeaveTypes || 'All Leave Types',
        allowClear: true
      });

      $('#statusFilter').select2({
        placeholder: labels.allStatuses || 'All Statuses',
        allowClear: true
      });
    }

    // Apply filters button
    $('#applyFilters').on('click', function() {
      applyCalendarFilters(calendar);
    });

    // Reset filters button
    $('#resetFilters').on('click', function() {
      // Reset all filter dropdowns to empty value
      $('#designationFilter').val('').trigger('change');
      $('#leaveTypeFilter').val('').trigger('change');
      $('#statusFilter').val('').trigger('change');

      // Apply filters to show all events
      applyCalendarFilters(calendar);
    });

    // Filter functions
    function applyCalendarFilters(calendar) {
      const designationFilter = $('#designationFilter').val();
      const leaveTypeFilter = $('#leaveTypeFilter').val();
      const statusFilter = $('#statusFilter').val();

      // Remove all events
      calendar.removeAllEvents();

      // Filter events
      const filteredEvents = calendarData.leaves.filter(event => {
        // Designation filter
        if (designationFilter && event.designationId != designationFilter) {
          return false;
        }

        // Leave type filter - compare with leave type ID
        if (leaveTypeFilter && event.leaveTypeId != parseInt(leaveTypeFilter)) {
          return false;
        }

        // Status filter
        if (statusFilter && event.status !== statusFilter) {
          return false;
        }

        return true;
      });

      // Add filtered events
      calendar.addEventSource(filteredEvents);
    }
    
    // Show leave details
    function showLeaveDetails(event) {
      const statusLabel = event.extendedProps.status === 'approved' ? (labels.approved || 'Approved') : (labels.pending || 'Pending');
      const modalContent = `
        <div class="modal fade" id="leaveDetailsModal" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">${labels.leaveDetails || 'Leave Details'}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                <div class="row mb-3">
                  <div class="col-sm-4">
                    <strong>${labels.employee || 'Employee'}:</strong>
                  </div>
                  <div class="col-sm-8">
                    ${event.extendedProps.user}
                  </div>
                </div>
                <div class="row mb-3">
                  <div class="col-sm-4">
                    <strong>${labels.leaveType || 'Leave Type'}:</strong>
                  </div>
                  <div class="col-sm-8">
                    <span class="badge" style="background-color: ${event.backgroundColor}">
                      ${event.extendedProps.leaveType}
                    </span>
                  </div>
                </div>
                <div class="row mb-3">
                  <div class="col-sm-4">
                    <strong>${labels.duration || 'Duration'}:</strong>
                  </div>
                  <div class="col-sm-8">
                    ${event.start.toLocaleDateString()} - ${new Date(event.end.getTime() - 86400000).toLocaleDateString()}
                    <br><small>${event.extendedProps.totalDays} ${labels.days || 'day(s)'}</small>
                  </div>
                </div>
                <div class="row mb-3">
                  <div class="col-sm-4">
                    <strong>${labels.status || 'Status'}:</strong>
                  </div>
                  <div class="col-sm-8">
                    <span class="badge bg-label-${event.extendedProps.status === 'approved' ? 'success' : 'warning'}">
                      ${statusLabel}
                    </span>
                  </div>
                </div>
                ${event.extendedProps.reason ? `
                <div class="row">
                  <div class="col-sm-4">
                    <strong>${labels.reason || 'Reason'}:</strong>
                  </div>
                  <div class="col-sm-8">
                    ${event.extendedProps.reason}
                  </div>
                </div>
                ` : ''}
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">${labels.close || 'Close'}</button>
              </div>
            </div>
          </div>
        </div>
      `;
      
      // Remove existing modal if any
      const existingModal = document.getElementById('leaveDetailsModal');
      if (existingModal) {
        existingModal.remove();
      }
      
      // Add modal to body
      document.body.insertAdjacentHTML('beforeend', modalContent);
      
      // Show modal
      const modal = new bootstrap.Modal(document.getElementById('leaveDetailsModal'));
      modal.show();
      
      // Remove modal from DOM when hidden
      document.getElementById('leaveDetailsModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
      });
    }
  }
  
  // Show toast notification
  function showToast(message, type = 'info') {
    const toastHtml = `
      <div class="bs-toast toast toast-placement-ex m-2 fade bg-${type === 'success' ? 'success' : 'primary'} top-0 end-0 show" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
          <i class="bx bx-${type === 'success' ? 'check' : 'info-circle'} me-2"></i>
          <div class="me-auto fw-semibold">${type === 'success' ? (labels.success || 'Success') : (labels.info || 'Info')}</div>
          <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
          ${message}
        </div>
      </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', toastHtml);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
      const toast = document.querySelector('.bs-toast');
      if (toast) {
        toast.remove();
      }
    }, 3000);
  }
});