'use strict';

$(function () {

  // --- Selectors ---
  const enrollmentsDataTableElement = $('.datatables-enrollments');
  const enrollUsersModalElement = $('#enrollUsersModal');
  const enrollUsersModal = enrollUsersModalElement.length ? new bootstrap.Modal(enrollUsersModalElement[0]) : null;
  const enrollUsersForm = $('#enrollUsersForm');
  const submitEnrollmentBtn = $('#submitEnrollmentBtn');
  const enrollUserSelect = $('#enrollUserIds');
  const enrollDesignationSelect = $('#enrollDesignationIds');
  const enrollGeneralError = $('#enrollUsersForm .general-error-message');

  // Progress Modal Selectors
  const progressModalElement = $('#enrollmentProgressModal');
  const progressModal = progressModalElement.length ? new bootstrap.Modal(progressModalElement[0]) : null;
  const progressModalLabel = $('#enrollmentProgressModalLabel');
  const progressModalLoading = $('#progress-modal-loading');
  const progressModalContent = $('#progress-modal-content');
  const progressUserName = $('#progress-user-name');
  const progressCourseTitle = $('#progress-course-title');
  const progressEnrollmentStatus = $('#progress-enrollment-status');
  const progressEnrolledAt = $('#progress-enrolled-at');
  const progressStartedAt = $('#progress-started-at');
  const progressCompletedAt = $('#progress-completed-at');
  const progressSummaryText = $('#progress-summary-text');
  const progressBarIndicator = $('#progress-bar-indicator');
  const progressLessonList = $('#modal-lesson-completion-list');

  // --- CSRF Setup ---
  $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': pageData.csrfToken } });

  // --- Initialize Plugins ---
  function initializeEnrollmentModalPlugins() {
    if (enrollUsersModalElement.length) {
      const modalBody = enrollUsersModalElement.find('.modal-body');
      enrollUserSelect.select2({
        placeholder: pageData.labels.selectEmployees,
        dropdownParent: modalBody,
        closeOnSelect: false
      });
      enrollDesignationSelect.select2({
        placeholder: pageData.labels.selectEmployees,
        dropdownParent: modalBody,
        closeOnSelect: false
      });
    }
  }
  initializeEnrollmentModalPlugins();

  // --- Helper Functions ---
  function resetEnrollmentFormValidation() {
    enrollUsersForm.find('.is-invalid').removeClass('is-invalid');
    enrollUsersForm.find('.invalid-feedback').text('').hide();
    enrollUsersForm.find('.select2-container').removeClass('is-invalid');
    enrollGeneralError.text('').hide();
  }

  function resetEnrollmentForm() {
    resetEnrollmentFormValidation();
    enrollUsersForm[0]?.reset();
    enrollUserSelect.val(null).trigger('change');
    enrollDesignationSelect.val(null).trigger('change');
    enrollGeneralError.text('').hide();
    submitEnrollmentBtn.text(pageData.labels.enrollSelectedUsers).prop('disabled', false);
  }

  function setEnrollmentButtonLoading(isLoading) {
    submitEnrollmentBtn.prop('disabled', isLoading);
    submitEnrollmentBtn.html(isLoading ? '<span class="spinner-border spinner-border-sm"></span> ' + pageData.labels.enrolling : pageData.labels.enrollSelectedUsers);
  }

  function resetProgressModal() {
    progressModalLabel.text(pageData.labels.progress);
    progressUserName.text(pageData.labels.na);
    progressCourseTitle.text(pageData.labels.na);
    progressEnrollmentStatus.text(pageData.labels.na).removeClass(function (index, className) { return (className.match(/(^|\s)badge\s\S+/g) || []).join(' '); });
    progressEnrolledAt.text(pageData.labels.na);
    progressStartedAt.text(pageData.labels.na);
    progressCompletedAt.text(pageData.labels.na);
    progressSummaryText.text(pageData.labels.progress);
    progressBarIndicator.css('width', '0%').attr('aria-valuenow', 0);
    progressLessonList.empty().append(`<li class="list-group-item text-muted">${pageData.labels.loadingLessonStatus}</li>`);
    progressModalLoading.hide();
    progressModalContent.show();
  }

  function displayEnrollmentValidationErrors(errors) {
    resetEnrollmentFormValidation();
    let firstErrorElement = null;
    for (const fieldName in errors) {
      let inputName = fieldName;
      if (fieldName.includes('.')) { inputName = fieldName.split('.')[0] + '[]'; }
      let errorMessage = errors[fieldName][0];
      const inputElement = enrollUsersForm.find(`[name="${inputName}"]`);
      let targetElement = inputElement;
      let feedbackElement = targetElement.closest('.mb-3').find('.invalid-feedback');

      if (!inputElement.length) { enrollGeneralError.append(`<div>${escapeHtml(fieldName)}: ${escapeHtml(errorMessage)}</div>`).show(); if (!firstErrorElement) firstErrorElement = enrollGeneralError; continue; }
      if (inputElement.hasClass('select2-hidden-accessible')) { targetElement = inputElement.siblings('.select2-container'); }

      if (targetElement.length) {
        targetElement.addClass('is-invalid');
        if (feedbackElement.length) { feedbackElement.text(errorMessage).show(); }
        else { targetElement.after(`<div class="invalid-feedback d-block">${errorMessage}</div>`); }
        if (!firstErrorElement) firstErrorElement = targetElement;
      }
    }
    if (firstErrorElement && firstErrorElement.hasClass('select2-container')) { firstErrorElement.prev('select').select2('open'); }
  }

  function escapeHtml(unsafe) {
    if (typeof unsafe !== 'string') return '';
    return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  }

  // --- DataTable Initialization ---
  let dtEnrollments;
  if (enrollmentsDataTableElement.length) {
    dtEnrollments = enrollmentsDataTableElement.DataTable({
      processing: true, serverSide: true,
      ajax: { url: pageData.urls.enrollmentsListAjax, type: 'GET' },
      columns: [
        { data: 'user', name: 'user', orderable: false, searchable: false },
        { data: 'status', name: 'status' },
        { data: 'progress', name: 'progress', orderable: false, searchable: false },
        { data: 'enrolled_at', name: 'enrolled_at' },
        { data: 'completed_at', name: 'completed_at' },
        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-center' }
      ],
      order: [[3, 'desc']],
      dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
      language: { search: '', searchPlaceholder: pageData.labels.searchEnrollments },
    });
  }

  // --- Enrollment Modal Handling ---
  if (enrollUsersModalElement.length) { enrollUsersModalElement.on('hidden.bs.modal', resetEnrollmentForm); }

  // Enroll Users Form Submission
  if (enrollUsersForm.length) {
    enrollUsersForm.on('submit', function(e) {
      e.preventDefault();
      resetEnrollmentFormValidation();

      const selectedUsers = enrollUserSelect.val() || [];
      const selectedDesignations = enrollDesignationSelect.val() || [];

      if (selectedUsers.length === 0 && selectedDesignations.length === 0) {
        showErrorToast(pageData.labels.pleaseSelectUsers);
        enrollUserSelect.siblings('.select2-container').addClass('is-invalid');
        enrollDesignationSelect.siblings('.select2-container').addClass('is-invalid');
        enrollGeneralError.text(pageData.labels.pleaseSelectUsers).show();
        return;
      }

      const payload = { user_ids: selectedUsers, designation_ids: selectedDesignations };
      setEnrollmentButtonLoading(true);

      $.ajax({
        url: pageData.urls.enrollmentsStore, method: 'POST', data: JSON.stringify(payload),
        contentType: 'application/json; charset=utf-8', dataType: 'json',
        success: function (response) {
          if (response.success) {
            enrollUsersModal?.hide();
            showSuccessToast(response.message);
            dtEnrollments?.ajax.reload(null, false);
          } else {
            showErrorToast(response.message || pageData.labels.operationFailed);
            enrollGeneralError.text(response.message || pageData.labels.operationFailed).show();
          }
        },
        error: function (jqXHR) {
          if (jqXHR.status === 422 && jqXHR.responseJSON?.errors) {
            displayEnrollmentValidationErrors(jqXHR.responseJSON.errors);
            showErrorToast(pageData.labels.validationFailed);
          } else {
            showErrorToast(jqXHR.responseJSON?.message || pageData.labels.anErrorOccurred);
          }
        },
        complete: function () { setEnrollmentButtonLoading(false); }
      });
    });
  }

  // --- Unenroll User Handling ---
  enrollmentsDataTableElement.on('click', '.delete-enrollment', function () {
    const button = $(this);
    const unenrollUrl = button.data('url');

    Swal.fire({
      title: pageData.labels.unenrollUser, text: pageData.labels.areYouSureUnenroll, icon: 'warning',
      showCancelButton: true, confirmButtonText: pageData.labels.yesUnenroll,
      customClass: { confirmButton: 'btn btn-danger me-3', cancelButton: 'btn btn-label-secondary' }, buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: unenrollUrl, method: 'POST', data: { _method: 'DELETE' }, dataType: 'json',
          success: function(response) {
            if (response.success) {
              showSuccessToast(response.message);
              dtEnrollments?.row(button.closest('tr')).remove().draw(false);
            } else { showErrorToast(response.message || pageData.labels.unenrollmentFailed); }
          },
          error: function(jqXHR) { showErrorToast(jqXHR.responseJSON?.message || pageData.labels.unenrollmentFailed); }
        });
      }
    });
  });

  // --- View Progress Modal Trigger ---
  enrollmentsDataTableElement.on('click', '.view-enrollment-progress', function () {
    const button = $(this);
    const url = button.data('url');

    resetProgressModal();
    progressModalContent.hide();
    progressModalLoading.show();
    progressModal?.show();

    $.ajax({
      url: url, type: 'GET', dataType: 'json',
      success: function(response) {
        progressModalLoading.hide();
        if (response.success && response.data) {
          const data = response.data;
          progressModalLabel.text(`${pageData.labels.progress} - ${data.userName}`);
          progressUserName.text(data.userName || pageData.labels.na);
          progressCourseTitle.text(data.courseTitle || pageData.labels.na);
          progressEnrollmentStatus.html(`<span class="badge ${data.statusClass || 'bg-label-secondary'}">${data.status || pageData.labels.na}</span>`);
          progressEnrolledAt.text(data.enrolledAt || '-');
          progressStartedAt.text(data.startedAt || '-');
          progressCompletedAt.text(data.completedAt || '-');
          progressSummaryText.text(`${pageData.labels.progress} (${data.completedCount}/${data.totalLessons})`);
          progressBarIndicator.css('width', `${data.progressPercent || 0}%`).attr('aria-valuenow', data.progressPercent || 0);

          progressLessonList.empty();
          if (data.lessons && data.lessons.length > 0) {
            data.lessons.forEach(lesson => {
              const iconClass = lesson.isCompleted ? 'bx bx-check-circle text-success' : 'bx bx-circle text-muted';
              const completionDate = lesson.isCompleted ? `<small class="text-muted ms-2">(${lesson.completedAt || pageData.labels.completed})</small>` : '';
              progressLessonList.append(`
                <li class="list-group-item d-flex justify-content-between align-items-center px-0">
                  <span>${escapeHtml(lesson.title)}</span>
                  <span><i class="${iconClass}"></i> ${completionDate}</span>
                </li>
              `);
            });
          } else {
            progressLessonList.append(`<li class="list-group-item px-0 text-muted">${pageData.labels.noLessonsFound}</li>`);
          }
          progressModalContent.show();
        } else {
          progressModalContent.show();
          progressLessonList.html(`<li class="list-group-item px-0 text-danger">${response.message || pageData.labels.couldNotLoadProgress}</li>`);
          showErrorToast(response.message || pageData.labels.couldNotLoadProgress);
        }
      },
      error: function(jqXHR) {
        progressModalLoading.hide();
        progressModalContent.show();
        progressLessonList.html(`<li class="list-group-item px-0 text-danger">${pageData.labels.errorLoadingProgress}</li>`);
        showErrorToast(jqXHR.responseJSON?.message || pageData.labels.errorLoadingProgress);
      }
    });
  });

});
