'use strict';

$(function () {
  // --- Variable Definitions ---
  var dtTaskTable = $('.datatables-onboarding-tasks');
  var taskForm = $('#onboardingTaskForm');
  var offcanvasElement = $('#offcanvasAddEditTask');
  var offcanvas = new bootstrap.Offcanvas(offcanvasElement[0]);

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

  // --- Helper: Reset Form Validation & Content ---
  function resetFormValidation(formElement) {
    const form = $(formElement);
    form.find('.is-invalid').removeClass('is-invalid');
    form.find('.invalid-feedback').text('');
  }

  function resetOffcanvasForm() {
    resetFormValidation(taskForm[0]);
    taskForm[0].reset();
    $('#onboarding_task_id').val('');
    $('#taskMethod').val('POST');
    $('#isActive').prop('checked', true);
    $('#submitTaskBtn').prop('disabled', false).text(pageData.labels.submit || 'Submit');
    taskForm.find('#taskType').val('').trigger('change');
  }

  // Reset form when offcanvas is hidden
  offcanvasElement.on('hidden.bs.offcanvas', function () {
    resetOffcanvasForm();
  });

  // --- DataTable Initialization ---
  if (dtTaskTable.length) {
    var dtTask = dtTaskTable.DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: pageData.urls.datatable,
        type: 'POST'
      },
      columns: [
        { data: 'id', name: 'id' },
        { data: 'title', name: 'title' },
        { data: 'description', name: 'description', orderable: false },
        { data: 'task_type_label', name: 'type' },
        { data: 'default_due_days', name: 'default_due_days', className: 'text-center' },
        { data: 'is_active', name: 'is_active', className: 'text-center', orderable: false, searchable: false },
        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-center' }
      ],
      order: [[0, 'desc']],
      dom: '<"row me-2"<"col-md-2"<"me-3"l>><"col-md-10"<"dt-action-buttons text-xl-end text-lg-start text-md-end text-start d-flex align-items-center justify-content-end flex-md-row flex-column mb-3 mb-md-0"fB>>>t<"row mx-2"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
      language: {
        sLengthMenu: '_MENU_',
        search: '',
        searchPlaceholder: pageData.labels.searchPlaceholder || 'Search Tasks..'
      },
      buttons: [],
      responsive: {}
    });
  }

  // --- Open Offcanvas for Create ---
  $('#addOnboardingTaskBtn').on('click', function () {
    resetOffcanvasForm();
    $('#offcanvasAddEditTaskLabel').text(pageData.labels.addTaskTemplate || 'Add Task Template');
    offcanvas.show();
  });

  // --- Open Offcanvas for Edit ---
  $(document).on('click', '.edit-onboarding-task', function () {
    var id = $(this).data('id');
    var editDataUrl = $(this).data('url');

    resetOffcanvasForm();

    $.ajax({
      url: editDataUrl, type: 'GET',
      beforeSend: function() {
        $('#offcanvasAddEditTaskLabel').text(pageData.labels.loadingData || 'Loading Data...');
      },
      success: function (response) {
        if (response.success && response.task) {
          const taskData = response.task;
          $('#offcanvasAddEditTaskLabel').text((pageData.labels.editTaskTemplate || 'Edit Task Template') + ' #' + taskData.id);
          $('#onboarding_task_id').val(taskData.id);
          $('#taskMethod').val('PUT');

          $('#taskTitle').val(taskData.title);
          $('#taskDescription').val(taskData.description);
          $('#defaultDueDays').val(taskData.defaultDueDays);
          $('#isActive').prop('checked', taskData.isActive);

          $('#taskType').val(taskData.type).trigger('change');

          offcanvas.show();
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: response.message || pageData.labels.failedToLoadData || 'Failed to load task data.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
          $('#offcanvasAddEditTaskLabel').text(pageData.labels.editTaskTemplate || 'Edit Task Template');
        }
      },
      error: function (jqXHR) {
        Swal.fire({
          icon: 'error',
          title: pageData.labels.error || 'Error',
          text: pageData.labels.anErrorFetchingData || 'An error occurred while fetching data.',
          customClass: { confirmButton: 'btn btn-danger' },
          buttonsStyling: false
        });
        $('#offcanvasAddEditTaskLabel').text(pageData.labels.editTaskTemplate || 'Edit Task Template');
      }
    });
  });

  // --- Form Submission (Create/Update) ---
  taskForm.on('submit', function (e) {
    e.preventDefault();
    resetFormValidation(this);

    var formData = new FormData(this);
    if (!formData.has('isActive')) {
      formData.set('isActive', '0');
    } else {
      formData.set('isActive', '1');
    }


    var id = $('#onboarding_task_id').val();
    var method = $('#taskMethod').val();
    var url = id ? (pageData.urls.base + '/' + id) : pageData.urls.store;
    var submitButton = $('#submitTaskBtn');

    if(method === 'PUT') {
      formData.append('_method', 'PUT');
    }

    submitButton.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> ' + (pageData.labels.processing || 'Processing...'));

    $.ajax({
      url: url, type: 'POST',
      data: formData, processData: false, contentType: false,
      success: function (response) {
        if (response.success) {
          Swal.fire({
            icon: 'success',
            title: pageData.labels.success || 'Success',
            text: response.message,
            timer: 1500,
            showConfirmButton: false,
            customClass: { confirmButton: 'btn btn-success' },
            buttonsStyling: false
          });
          offcanvas.hide();
          if (dtTask) dtTask.ajax.reload(null, false);
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: response.message || pageData.labels.operationFailed || 'Operation failed.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }
      },
      error: function (jqXHR) {
        if (jqXHR.status === 422 && jqXHR.responseJSON?.errors) {
          $.each(jqXHR.responseJSON.errors, function (key, value) {
            let inputName = key;
            $('[name="' + inputName + '"]').addClass('is-invalid').siblings('.invalid-feedback').text(value[0]);
          });
          $('.is-invalid').first().focus();
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: jqXHR.responseJSON?.message || pageData.labels.anErrorOccurred || 'An error occurred.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }
      },
      complete: function () {
        submitButton.prop('disabled', false).text(pageData.labels.submit || 'Submit');
      }
    });
  });

  // --- Toggle Status Handling ---
  $(document).on('change', '.toggle-task-status', function () {
    var checkbox = $(this);
    var url = checkbox.data('url');
    var status = checkbox.is(':checked');
    var label = checkbox.siblings('.switch-label');

    $.ajax({
      url: url,
      type: 'PUT',
      data: {},
      success: function(response) {
        if (response.success) {
          label.text(response.newStatus ? (pageData.labels.active || 'Active') : (pageData.labels.inactive || 'Inactive'));
        } else {
          checkbox.prop('checked', !status);
          label.text(status ? (pageData.labels.inactive || 'Inactive') : (pageData.labels.active || 'Active'));
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: response.message || pageData.labels.failedToUpdate || 'Failed to update status.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }
      },
      error: function(jqXHR) {
        checkbox.prop('checked', !status);
        label.text(status ? (pageData.labels.inactive || 'Inactive') : (pageData.labels.active || 'Active'));
        Swal.fire({
          icon: 'error',
          title: pageData.labels.error || 'Error',
          text: pageData.labels.anErrorOccurred || 'An error occurred.',
          customClass: { confirmButton: 'btn btn-danger' },
          buttonsStyling: false
        });
      }
    });
  });


  // --- Delete Handling ---
  $(document).on('click', '.delete-onboarding-task', function () {
    var button = $(this);
    var deleteUrl = button.data('url');

    Swal.fire({
      title: pageData.labels.areYouSure || 'Are you sure?',
      text: pageData.labels.deleteWarning || "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: pageData.labels.yesDelete || 'Yes, delete it!',
      cancelButtonText: pageData.labels.cancel || 'Cancel',
      customClass: { confirmButton: 'btn btn-primary me-3', cancelButton: 'btn btn-label-secondary' },
      buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: deleteUrl, type: 'DELETE',
          success: function (response) {
            if (response.success) {
              Swal.fire({
                icon: 'success',
                title: pageData.labels.deleted || 'Deleted!',
                text: response.message,
                customClass: { confirmButton: 'btn btn-success' },
                buttonsStyling: false
              });
              if (dtTask) dtTask.row(button.closest('tr')).remove().draw(false);
            } else {
              Swal.fire({
                icon: 'error',
                title: pageData.labels.error || 'Error!',
                text: response.message || pageData.labels.failedToDelete || 'Failed to delete.',
                customClass: { confirmButton: 'btn btn-danger' },
                buttonsStyling: false
              });
            }
          },
          error: function (jqXHR) {
            Swal.fire({
              icon: 'error',
              title: pageData.labels.error || 'Error!',
              text: jqXHR.responseJSON?.message || pageData.labels.anErrorOccurred || 'An error occurred.',
              customClass: { confirmButton: 'btn btn-danger' },
              buttonsStyling: false
            });
          }
        });
      }
    });
  });


});
