// Helper function to format datetime strings
function formatDateTime(dateTimeString) {
  if (!dateTimeString) return 'N/A';

  try {
    // Try to parse the datetime string
    const date = new Date(dateTimeString);

    // Check if date is valid
    if (isNaN(date.getTime())) {
      // If it's already formatted, return as is
      return dateTimeString;
    }

    return date.toLocaleString();
  } catch (e) {
    // If parsing fails, return the original string
    return dateTimeString;
  }
}

$(function() {
  // Initialize DataTable
  const table = $('#leavesTable').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
      url: pageData.urls.datatable,
      data: function(d) {
        d.status = $('#filterStatus').val();
        d.leave_type_id = $('#filterLeaveType').val();
        d.date_from = $('#filterDateFrom').val();
        d.date_to = $('#filterDateTo').val();
      }
    },
    columns: [
      { data: 'created_at', name: 'created_at' },
      { data: 'leave_type', name: 'leave_type' },
      { data: 'from_date', name: 'from_date' },
      { data: 'to_date', name: 'to_date' },
      { data: 'total_days', name: 'total_days' },
      { data: 'status', name: 'status' },
      { data: 'actions', name: 'actions', orderable: false, searchable: false }
    ],
    order: [[0, 'desc']],
    dom: '<"card-header d-flex flex-wrap"<"me-5 ms-n2"f><"d-flex justify-content-start justify-content-md-end align-items-baseline gap-2"<"dt-action-buttons"B>l>>t<"row mx-1"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
    displayLength: 10,
    lengthMenu: [10, 25, 50, 100],
    buttons: [],
    language: {
      search: '',
      searchPlaceholder: pageData.labels.search,
      processing: pageData.labels.processing,
      lengthMenu: pageData.labels.lengthMenu,
      info: pageData.labels.info,
      infoEmpty: pageData.labels.infoEmpty,
      infoFiltered: pageData.labels.infoFiltered,
      emptyTable: pageData.labels.emptyTable,
      zeroRecords: pageData.labels.zeroRecords,
      paginate: pageData.labels.paginate
    }
  });

  // Apply filters
  $('#filterStatus, #filterLeaveType, #filterDateFrom, #filterDateTo').on('change', function() {
    table.ajax.reload();
  });
});

// View leave details
function viewMyLeave(id) {
  // Show offcanvas
  const offcanvasElement = document.getElementById('leaveDetailsOffcanvas');
  const offcanvas = new bootstrap.Offcanvas(offcanvasElement);
  offcanvas.show();

  // Reset content to loading
  document.getElementById('leaveDetailsContent').innerHTML = `
    <div class="text-center">
      <div class="spinner-border spinner-border-sm" role="status">
        <span class="visually-hidden">${pageData.labels.loading}</span>
      </div>
    </div>
  `;

  // Fetch leave details
  fetch(pageData.urls.show.replace('__ID__', id), {
    headers: {
      'Accept': 'application/json',
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.status === 'success') {
      const leave = data.data.leave_request;
      const leaveType = data.data.leave_type;

      // Format status badge and label
      const statusBadge = {
        'pending': 'bg-label-warning',
        'approved': 'bg-label-success',
        'rejected': 'bg-label-danger',
        'cancelled': 'bg-label-secondary'
      };

      const statusLabels = {
        'pending': pageData.labels.pending,
        'approved': pageData.labels.approved,
        'rejected': pageData.labels.rejected,
        'cancelled': pageData.labels.cancelled
      };

      // Build the content HTML
      const content = `
        <div class="leave-details">
          <!-- Status -->
          <div class="mb-4 text-center">
            <span class="badge ${statusBadge[leave.status] || 'bg-label-primary'} fs-6">
              ${statusLabels[leave.status] || leave.status}
            </span>
          </div>

          <!-- Leave Type -->
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.leaveType}</label>
            <p class="mb-0 fw-semibold">${leaveType.name}</p>
          </div>

          <!-- Date Range -->
          <div class="row mb-3">
            <div class="col-6">
              <label class="form-label text-muted small">${pageData.labels.fromDate}</label>
              <p class="mb-0">${leave.from_date}</p>
            </div>
            <div class="col-6">
              <label class="form-label text-muted small">${pageData.labels.toDate}</label>
              <p class="mb-0">${leave.to_date}</p>
            </div>
          </div>

          <!-- Total Days -->
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.totalDays}</label>
            <p class="mb-0">
              <span class="badge bg-label-primary">${leave.total_days} ${pageData.labels.days}</span>
              ${leave.is_half_day ? '<span class="badge bg-label-info ms-1">' + pageData.labels.halfDay + '</span>' : ''}
            </p>
          </div>

          <!-- Reason -->
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.reasonForLeave}</label>
            <p class="mb-0">${leave.user_notes || pageData.labels.na}</p>
          </div>

          <!-- Emergency Contact -->
          ${leave.emergency_contact ? `
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.emergencyContact}</label>
            <p class="mb-0">${leave.emergency_contact} ${leave.emergency_phone ? '(' + leave.emergency_phone + ')' : ''}</p>
          </div>
          ` : ''}

          <!-- Traveling Abroad -->
          ${leave.is_abroad ? `
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.travelingLocation}</label>
            <p class="mb-0">${leave.abroad_location || pageData.labels.na}</p>
          </div>
          ` : ''}

          <!-- Supporting Document -->
          ${leave.document ? `
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.supportingDocument}</label>
            <p class="mb-0">
              <a href="/storage/${leave.document}" target="_blank" class="btn btn-sm btn-label-primary">
                <i class="bx bx-file me-1"></i> ${pageData.labels.viewDocument}
              </a>
            </p>
          </div>
          ` : ''}

          <!-- Applied On -->
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.appliedOn}</label>
            <p class="mb-0">${formatDateTime(leave.created_at)}</p>
          </div>

          <!-- Approved/Rejected By -->
          ${leave.approved_by_id ? `
          <div class="mb-3">
            <label class="form-label text-muted small">
              ${leave.status === 'approved' ? pageData.labels.approvedBy : pageData.labels.rejectedBy}
            </label>
            <p class="mb-0">${data.data.approved_by ? data.data.approved_by.name : pageData.labels.na}</p>
          </div>
          ` : ''}

          <!-- Admin Notes -->
          ${leave.admin_notes ? `
          <div class="mb-3">
            <label class="form-label text-muted small">${pageData.labels.adminNotes}</label>
            <p class="mb-0">${leave.admin_notes}</p>
          </div>
          ` : ''}

          <!-- Actions -->
          ${leave.status === 'pending' ? `
          <div class="d-grid gap-2">
            <button type="button" class="btn btn-danger" onclick="cancelMyLeave(${leave.id}); bootstrap.Offcanvas.getInstance(document.getElementById('leaveDetailsOffcanvas')).hide();">
              <i class="bx bx-x me-1"></i> ${pageData.labels.cancelRequest}
            </button>
          </div>
          ` : ''}
        </div>
      `;

      document.getElementById('leaveDetailsContent').innerHTML = content;
    }
  })
  .catch(error => {
    console.error('Error fetching leave details:', error);
    document.getElementById('leaveDetailsContent').innerHTML = `
      <div class="alert alert-danger">
        <i class="bx bx-error-circle me-1"></i>
        ${pageData.labels.failedToLoad}
      </div>
    `;
  });
}

// Cancel leave request
function cancelMyLeave(id) {
  Swal.fire({
    title: pageData.labels.cancelTitle,
    text: pageData.labels.confirmCancel,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: pageData.labels.cancelButton,
    cancelButtonText: pageData.labels.cancelButtonText,
    customClass: {
      confirmButton: 'btn btn-danger me-3',
      cancelButton: 'btn btn-label-secondary'
    },
    buttonsStyling: false
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: pageData.urls.cancel.replace('__ID__', id),
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
          if (response.status === 'success') {
            Swal.fire({
              icon: 'success',
              title: pageData.labels.success,
              text: pageData.labels.requestCancelled,
              customClass: {
                confirmButton: 'btn btn-success'
              },
              buttonsStyling: false
            });
            $('#leavesTable').DataTable().ajax.reload();
          }
        },
        error: function(xhr) {
          let message = pageData.labels.failedToCancel;

          // Check for error message in different response formats
          if (xhr.responseJSON) {
            if (xhr.responseJSON.data && typeof xhr.responseJSON.data === 'string') {
              message = xhr.responseJSON.data;
            } else if (xhr.responseJSON.message) {
              message = xhr.responseJSON.message;
            } else if (xhr.responseJSON.errors) {
              const errors = Object.values(xhr.responseJSON.errors).flat();
              message = errors.join('\n');
            }
          }

          Swal.fire({
            icon: 'error',
            title: pageData.labels.error,
            text: message,
            customClass: {
              confirmButton: 'btn btn-danger'
            },
            buttonsStyling: false
          });
        }
      });
    }
  });
}

// Make functions available globally
window.viewMyLeave = viewMyLeave;
window.cancelMyLeave = cancelMyLeave;