'use strict';

$(function () {
  // CSRF setup
  $.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
  });

  let dataTable;
  const offcanvasEl = document.getElementById('offcanvasDesignation');
  const offcanvas = offcanvasEl ? new bootstrap.Offcanvas(offcanvasEl) : null;

  // Initialize Select2
  $('#designationDepartment').select2({
    dropdownParent: $('#offcanvasDesignation'),
    placeholder: pageData.labels.selectDepartment,
    allowClear: true
  });

  // Initialize DataTable
  dataTable = $('#designationsTable').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
      url: pageData.urls.datatable,
      type: 'GET'
    },
    columns: [
      { data: 'id', name: 'id' },
      { data: 'name', name: 'name' },
      { data: 'code', name: 'code' },
      {
        data: 'department_name',
        name: 'department_name',
        render: function (data) {
          return data || pageData.labels.noDepartment;
        }
      },
      {
        data: 'notes',
        name: 'notes',
        render: function (data) {
          return data || pageData.labels.na;
        }
      },
      {
        data: 'status',
        name: 'status',
        orderable: false,
        render: function (data) {
          if (data === 'active') {
            return `<span class="badge bg-label-success">${pageData.labels.active}</span>`;
          }
          return `<span class="badge bg-label-secondary">${pageData.labels.inactive}</span>`;
        }
      },
      {
        data: 'id',
        name: 'actions',
        orderable: false,
        searchable: false,
        render: function (data, type, row) {
          return `
            <div class="dropdown">
              <button type="button" class="btn btn-sm btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                <i class="bx bx-dots-vertical-rounded"></i>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li>
                  <a class="dropdown-item edit-record" href="javascript:void(0);" data-id="${row.id}">
                    <i class="bx bx-edit me-2"></i>${pageData.labels.edit}
                  </a>
                </li>
                <li>
                  <a class="dropdown-item toggle-status" href="javascript:void(0);" data-id="${row.id}" data-status="${row.status}">
                    <i class="bx ${row.status === 'active' ? 'bx-x-circle' : 'bx-check-circle'} me-2"></i>${row.status === 'active' ? pageData.labels.deactivate : pageData.labels.activate}
                  </a>
                </li>
                <li>
                  <a class="dropdown-item text-danger delete-record" href="javascript:void(0);" data-id="${row.id}">
                    <i class="bx bx-trash me-2"></i>${pageData.labels.delete}
                  </a>
                </li>
              </ul>
            </div>
          `;
        }
      }
    ],
    order: [[0, 'desc']],
    pageLength: 25,
    language: {
      processing: pageData.labels.processing,
      emptyTable: pageData.labels.noData,
      search: pageData.labels.search,
      lengthMenu: pageData.labels.lengthMenu,
      info: pageData.labels.info,
      infoEmpty: pageData.labels.infoEmpty,
      infoFiltered: pageData.labels.infoFiltered,
      zeroRecords: pageData.labels.zeroRecords,
      paginate: pageData.labels.paginate,
      searchPlaceholder: pageData.labels.searchDesignation
    }
  });

  // Add Designation button click
  $('#btnAddDesignation').on('click', function () {
    resetForm();
    $('#offcanvasDesignationLabel').text(pageData.labels.addDesignation);
    loadDepartments();
  });

  // Load departments for dropdown
  function loadDepartments(selectedId = null) {
    $.get(pageData.urls.departments, function (response) {
      const $select = $('#designationDepartment');
      $select.empty().append(`<option value="">${pageData.labels.selectDepartment}</option>`);

      if (response.success && response.data) {
        response.data.forEach(function (dept) {
          const selected = dept.id == selectedId ? 'selected' : '';
          $select.append(`<option value="${dept.id}" ${selected}>${dept.name}</option>`);
        });
      }
      $select.trigger('change');
    });
  }

  // Edit record
  $(document).on('click', '.edit-record', function () {
    const id = $(this).data('id');
    const url = pageData.urls.show.replace(':id', id);

    resetForm();
    $('#offcanvasDesignationLabel').text(pageData.labels.editDesignation);

    $.get(url, function (response) {
      if (response.success) {
        const designation = response.data;
        loadDepartments(designation.department_id);

        $('#designationId').val(designation.id);
        $('#designationName').val(designation.name);
        $('#designationCode').val(designation.code);
        $('#designationNotes').val(designation.notes);

        offcanvas.show();
      }
    }).fail(function (xhr) {
      Swal.fire({
        icon: 'error',
        title: pageData.labels.error,
        text: xhr.responseJSON?.message || pageData.labels.genericError,
        customClass: { confirmButton: 'btn btn-danger' },
        buttonsStyling: false
      });
    });
  });

  // Form submit
  $('#designationForm').on('submit', function (e) {
    e.preventDefault();
    clearValidation();

    const id = $('#designationId').val();
    const isEdit = id !== '';
    const url = isEdit ? pageData.urls.update.replace(':id', id) : pageData.urls.store;

    const formData = {
      name: $('#designationName').val(),
      code: $('#designationCode').val(),
      department_id: $('#designationDepartment').val() || null,
      notes: $('#designationNotes').val()
    };

    if (isEdit) {
      formData._method = 'PUT';
    }

    const $btn = $('#btnSaveDesignation');
    const originalText = $btn.html();
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>' + pageData.labels.saving);

    $.ajax({
      url: url,
      type: 'POST',
      data: formData,
      success: function (response) {
        if (response.success) {
          offcanvas.hide();
          Swal.fire({
            icon: 'success',
            title: pageData.labels.success,
            text: isEdit ? pageData.labels.designationUpdated : pageData.labels.designationCreated,
            customClass: { confirmButton: 'btn btn-success' },
            buttonsStyling: false
          });
          dataTable.ajax.reload();
        }
      },
      error: function (xhr) {
        if (xhr.status === 422 && xhr.responseJSON?.errors) {
          showValidationErrors(xhr.responseJSON.errors);
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error,
            text: xhr.responseJSON?.message || pageData.labels.genericError,
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
        }
      },
      complete: function () {
        $btn.prop('disabled', false).html(originalText);
      }
    });
  });

  // Toggle status
  $(document).on('click', '.toggle-status', function () {
    const id = $(this).data('id');
    const currentStatus = $(this).data('status');
    const url = pageData.urls.toggleStatus.replace(':id', id);

    const confirmText = currentStatus === 'active'
      ? pageData.labels.confirmDeactivate
      : pageData.labels.confirmActivate;

    Swal.fire({
      title: pageData.labels.confirmStatusChange,
      text: confirmText,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: pageData.labels.yesChange,
      cancelButtonText: pageData.labels.cancel,
      customClass: {
        confirmButton: 'btn btn-primary me-3',
        cancelButton: 'btn btn-label-secondary'
      },
      buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: url,
          type: 'POST',
          success: function (response) {
            if (response.success) {
              Swal.fire({
                icon: 'success',
                title: pageData.labels.success,
                text: pageData.labels.statusUpdated,
                customClass: { confirmButton: 'btn btn-success' },
                buttonsStyling: false
              });
              dataTable.ajax.reload();
            }
          },
          error: function (xhr) {
            Swal.fire({
              icon: 'error',
              title: pageData.labels.error,
              text: xhr.responseJSON?.message || pageData.labels.genericError,
              customClass: { confirmButton: 'btn btn-danger' },
              buttonsStyling: false
            });
          }
        });
      }
    });
  });

  // Delete record
  $(document).on('click', '.delete-record', function () {
    const id = $(this).data('id');
    const url = pageData.urls.destroy.replace(':id', id);

    Swal.fire({
      title: pageData.labels.confirmDelete,
      text: pageData.labels.confirmDeleteText,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: pageData.labels.yesDelete,
      cancelButtonText: pageData.labels.cancel,
      customClass: {
        confirmButton: 'btn btn-danger me-3',
        cancelButton: 'btn btn-label-secondary'
      },
      buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: url,
          type: 'DELETE',
          success: function (response) {
            if (response.success) {
              Swal.fire({
                icon: 'success',
                title: pageData.labels.deleted,
                text: pageData.labels.designationDeleted,
                customClass: { confirmButton: 'btn btn-success' },
                buttonsStyling: false
              });
              dataTable.ajax.reload();
            }
          },
          error: function (xhr) {
            Swal.fire({
              icon: 'error',
              title: pageData.labels.error,
              text: xhr.responseJSON?.message || pageData.labels.genericError,
              customClass: { confirmButton: 'btn btn-danger' },
              buttonsStyling: false
            });
          }
        });
      }
    });
  });

  // Reset form
  function resetForm() {
    $('#designationForm')[0].reset();
    $('#designationId').val('');
    $('#designationDepartment').val('').trigger('change');
    clearValidation();
  }

  // Clear validation errors
  function clearValidation() {
    $('#designationForm .is-invalid').removeClass('is-invalid');
    $('#designationForm .invalid-feedback').text('');
  }

  // Show validation errors
  function showValidationErrors(errors) {
    Object.keys(errors).forEach(function (field) {
      const $input = $(`#designation${field.charAt(0).toUpperCase() + field.slice(1)}`);
      if ($input.length) {
        $input.addClass('is-invalid');
        $input.siblings('.invalid-feedback').text(errors[field][0]);
      }
    });
  }

  // Reset form when offcanvas is closed
  if (offcanvasEl) {
    offcanvasEl.addEventListener('hidden.bs.offcanvas', function () {
      resetForm();
    });
  }
});
