'use strict';

$(function () {
  // Variable definition
  var dtJobOpeningTable = $('.datatables-job-openings');
  var jobOpeningForm = $('#jobOpeningForm');
  var statusFilter = $('#statusFilter');
  var teamFilter = $('#teamFilter');
  var offcanvasElement = $('#offcanvasAddEditJobOpening');
  var offcanvas = new bootstrap.Offcanvas(offcanvasElement[0]);
  var select2 = $('.select2');

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

  // Init Select2
  if (select2.length) {
    select2.each(function () {
      var $this = $(this);
      $this.wrap('<div class="position-relative"></div>').select2({
        placeholder: pageData.labels.selectValue || 'Select value',
        dropdownParent: $this.parent()
      });
    });
  }

  // Date Picker
  const flatpickrDate = document.querySelector('#closesAt');
  if (flatpickrDate) {
    flatpickrDate.flatpickr({
      monthSelectorType: 'static',
      altInput: true,
      altFormat: 'M j, Y',
      dateFormat: 'Y-m-d',
      minDate: 'today'
    });
  }


  // --- 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(jobOpeningForm[0]);
    jobOpeningForm[0].reset();
    $('#job_opening_id').val('');
    $('#jobOpeningMethod').val('POST');
    jobOpeningForm.find('select.select2').val('').trigger('change');
    const closesAtPicker = document.querySelector('#closesAt')._flatpickr;
    if (closesAtPicker) {
      closesAtPicker.clear();
    }
    $('#submitJobOpeningBtn').prop('disabled', false).text(pageData.labels.submit || 'Submit');
  }

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


  // --- DataTable Initialization ---
  if (dtJobOpeningTable.length) {
    var dtJobOpening = dtJobOpeningTable.DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: pageData.urls.datatable,
        type: 'POST',
        data: function (d) {
          d.statusFilter = statusFilter.val();
          d.teamFilter = teamFilter.val();
        }
      },
      columns: [
        { data: 'id', name: 'id' },
        { data: 'title', name: 'title' },
        { data: 'teamName', name: 'team.name', orderable: false, searchable: false },
        { data: 'location', name: 'location' },
        { data: 'job_type', name: 'job_type' },
        { data: 'applications_count', name: 'applications_count', searchable: false, orderable: true, className: 'text-center' },
        { data: 'status', name: 'status' },
        { data: 'published_at', name: 'published_at' },
        { 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..'
      },
      buttons: [],
      responsive: {
        details: {
          display: $.fn.dataTable.Responsive.display.modal({
            header: function (row) {
              var data = row.data();
              return (pageData.labels.detailsOf || 'Details of') + ' ' + data['title'];
            }
          }),
          type: 'column',
          renderer: function (api, rowIdx, columns) {
            var data = $.map(columns, function (col, i) {
              return col.title !== '' ? '<tr data-dt-row="' + col.rowIndex + '" data-dt-column="' + col.columnIndex + '">' + '<td>' + col.title + ':' + '</td> ' + '<td>' + col.data + '</td>' + '</tr>' : '';
            }).join('');
            return data ? $('<table class="table"/><tbody />').append(data) : false;
          }
        }
      }
    });
  }

  // --- Filter Changes ---
  statusFilter.add(teamFilter).on('change', function () {
    dtJobOpening.ajax.reload();
  });

  // --- Open Offcanvas for Create ---
  $('#addJobOpeningBtn').on('click', function () {
    resetOffcanvasForm();
    $('#offcanvasAddEditJobOpeningLabel').text(pageData.labels.addJobOpening || 'Add Job Opening');
    offcanvas.show();
  });


  // --- Open Offcanvas for Edit ---
  $(document).on('click', '.edit-job-opening', function () {
    var id = $(this).data('id');
    var editDataUrl = pageData.urls.base + '/' + id + '/edit';

    resetOffcanvasForm();

    $.ajax({
      url: editDataUrl,
      type: 'GET',
      beforeSend: function() {
        $('#offcanvasAddEditJobOpeningLabel').text(pageData.labels.loadingData || 'Loading Data...');
      },
      success: function (response) {
        if (response.success && response.jobOpening) {
          const jobData = response.jobOpening;
          $('#offcanvasAddEditJobOpeningLabel').text((pageData.labels.editJobOpening || 'Edit Job Opening') + ' #' + jobData.id);
          $('#job_opening_id').val(jobData.id);
          $('#jobOpeningMethod').val('PUT');

          $('#title').val(jobData.title);
          $('#description').val(jobData.description);
          $('#location').val(jobData.location);
          $('#teamId').val(jobData.teamId).trigger('change');
          $('#jobType').val(jobData.jobType);
          $('#experienceLevel').val(jobData.experienceLevel);
          $('#skillsRequired').val(jobData.skillsRequired);
          $('#status').val(jobData.status).trigger('change');

          const closesAtPicker = document.querySelector('#closesAt')._flatpickr;
          if (closesAtPicker && jobData.closesAt) {
            closesAtPicker.setDate(jobData.closesAt, true);
          } else if (closesAtPicker) {
            closesAtPicker.clear();
          }


          offcanvas.show();
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: response.message || pageData.labels.failedToLoadData || 'Failed to load job opening data.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }
      },
      error: function (jqXHR) {
        let message = pageData.labels.anErrorFetchingData || 'An error occurred while fetching data.';
        if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
          message = jqXHR.responseJSON.message;
        }
        Swal.fire({
          icon: 'error',
          title: pageData.labels.error || 'Error',
          html: message,
          customClass: { confirmButton: 'btn btn-danger' },
          buttonsStyling: false
        });
      }
    });
  });


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

    var formData = new FormData(this);
    var id = $('#job_opening_id').val();
    var method = $('#jobOpeningMethod').val();
    var url = id ? (pageData.urls.base + '/' + id) : pageData.urls.store;
    var submitButton = $('#submitJobOpeningBtn');

    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();
          dtJobOpening.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) {
        console.error('Submit Error:', jqXHR);
        let message = pageData.labels.anErrorOccurred || 'An error occurred.';
        if (jqXHR.status === 422 && jqXHR.responseJSON?.errors) {
          message = jqXHR.responseJSON.message || pageData.labels.correctErrors || 'Please correct the errors below.';
          $.each(jqXHR.responseJSON.errors, function (key, value) {
            let inputName = key;
            let input = $('[name="' + inputName + '"]');
            input.addClass('is-invalid').siblings('.invalid-feedback').text(value[0]);
            if (input.hasClass('select2-hidden-accessible')) {
              input.siblings('.select2-container').addClass('is-invalid');
            }
          });
          $('.is-invalid').first().focus();

        } else if (jqXHR.responseJSON?.message) {
          message = jqXHR.responseJSON.message;
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            html: message,
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            html: message + ' (' + jqXHR.status + ' ' + jqXHR.statusText + ')',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }

      },
      complete: function () {
        submitButton.prop('disabled', false).text(pageData.labels.submit || 'Submit');
      }
    });
  });


  // --- Delete Handling ---
  $(document).on('click', '.delete-job-opening', function () {
    var id = $(this).data('id');
    var deleteUrl = $(this).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
              });
              dtJobOpening.ajax.reload(null, 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) {
            let message = pageData.labels.anErrorDuringDeletion || 'An error occurred during deletion.';
            if (jqXHR.responseJSON?.message) { message = jqXHR.responseJSON.message; }
            Swal.fire({
              icon: 'error',
              title: pageData.labels.error || 'Error!',
              text: message,
              customClass: { confirmButton: 'btn btn-danger' },
              buttonsStyling: false
            });
          }
        });
      }
    });
  });


});
