'use strict';
flatpickr("#send_datetime", {
    enableTime: true,
    time_24hr: false, // Use 12-hour format with AM/PM
    minDate: "today",
    dateFormat: "Y-m-d h:i K", // User-friendly format
    defaultDate: document.querySelector("#send_datetime").value, // Pre-filled value from server
    disableMobile: true,
    onReady: function (selectedDates, dateStr, instance) {
        // Trigger the same behavior as onChange for the default value
        handleDateChange(instance.selectedDates[0], dateStr);
    },
    onChange: function (selectedDates, dateStr, instance) {
        if (selectedDates.length > 0) {
            handleDateChange(selectedDates[0], dateStr);
        }
    },
});

$("#send").change(function() {
  $("#send-datetime").slideToggle('slow');
});

function onCancel(){ $('#smartwizard').smartWizard("reset"); }

function submitFrom(operation, msg){ 
  swal({
    title: '',
    text: msg,
    type: "warning",
    showCancelButton: true,
    cancelButtonClass: "btn-danger",
    confirmButtonClass: "btn-success",
    confirmButtonText: "Yes",
    closeOnConfirm: true
  }, function(){
    $("#operation").val(operation);
    $('#frm-schedule').submit(); 
  });
}


function provideContent(idx, stepDirection, stepPosition, selStep, callback) {
  callback();
}


function ucfirst(str) {
  if (!str) return ''; // Handle empty strings
  return str.charAt(0).toUpperCase() + str.slice(1);
}

  // Helper function to get selected labels
function getSelectedLabels(choicesInstance) {
  if (!choicesInstance) return [];
  const selectedValues = choicesInstance.getValue(true); // ["8", "15", "17"]
  const allOptions = choicesInstance.passedElement.element.options;
  return selectedValues.map(value => {
    const option = Array.from(allOptions).find(option => option.value === value);
    return option ? option.text : ''; // Return the text if found, otherwise empty string
  });
}


$(function() {

// Initialize Choices.js for #sending_server_ids and #list_ids only when the step is shown
$("#smartwizard").on("showStep", function(e, anchorObject, stepIndex, stepDirection, stepPosition) {

  $('#smartwizard .nav-link').addClass('text-primary');
  $('#smartwizard .sw-toolbar-elm .btn').addClass('btn-primary');

  // Enable/disable navigation buttons based on step position
  $("#prev-btn").removeClass('disabled').prop('disabled', false);
  $("#next-btn").removeClass('disabled').prop('disabled', false);
  if (stepPosition === 'first') {
    $("#prev-btn").addClass('disabled').prop('disabled', true);
  } else if (stepPosition === 'last') {
    $("#next-btn").addClass('disabled').prop('disabled', true);
  }

  // On the final step, capture input values and display them in the review section
  if (stepIndex === 3) {
    const dataFromDetail = {
      sending_server: `As defined for sending server`,
      list: `As defined for list`,
      custom: `Custom`,
    };
    const name = $("#name").val();
    const selectedRadioValue = $("input[name='from_detail']:checked").val();
    const email_subject = $("#email_subject").val();
    const send = $("#send").val();
    const send_datetime = $("#send_datetime").val();
    const speed = $("#speed").val();
    const duration = $("#duration").val();
    const limit = $("#limit").val();
    const from_name = $("#from_name").val();
    const from_email = $("#from_email_part1").val()+'@'+$("#from_email_part2").val();
    const reply_email = $("#reply_email").val();

    let custom_data;
    
    let reviewHtml = `
      <p><strong>Name:</strong> ${name || "---"}</p>
      <p><strong>From Detail:</strong> ${dataFromDetail[selectedRadioValue] || "---"}</p>`; // Initial definition

      if($("input[name='from_detail']:checked").val() == 'custom') {
       reviewHtml += `
            <p><strong>From Name:</strong> ${from_name || "---"}</p>
            <p><strong>From Email:</strong> ${from_email|| "---"}</p>
            <p><strong>Reply Email:</strong> ${reply_email || "---"}</p>
          `;
      }

      reviewHtml += `
      <p><strong>Email Subject:</strong> ${email_subject || "---"}</p>
      <p><strong>Send:</strong> ${ucfirst(send) || "---"}</p>
      <p><strong>Send at:</strong> ${send_datetime || "---"}</p>
      <p><strong>Speed:</strong> ${speed == "unlimited" ? "Maximum" : ucfirst(speed)}</p>
      <p><strong>Limit:</strong> ${speed == "unlimited" ? "---" : (limit+"/"+ucfirst(duration))}</p>
    `;
    $("#review-section").html(reviewHtml);

    // Display sending server choices
    if (multipleSendingServers) {
      const selectedLabels = getSelectedLabels(multipleSendingServers);
      $("#review-sending-servers").text(selectedLabels.join(", "));
    }

    // Display list choices
    if (multipleLists) {
      const selectedLabels = getSelectedLabels(multipleLists);
      $("#review-lists").text(selectedLabels.join(", "));
    }
  }

  // Update the current step info in the UI
  let stepInfo = $('#smartwizard').smartWizard("getStepInfo");
  $("#sw-current-step").text(stepInfo.currentStep + 1);
  $("#sw-total-step").text(stepInfo.totalSteps);
});

// Smart Wizard
$('#smartwizard').smartWizard({
    selected: 0,
    theme: 'square',
    transition: {
        animation: 'fade'
    },
    toolbar: {
        showNextButton: true,
        showPreviousButton: true,
        position: 'top',
        extraHtml: `<span class="ps-1"></span>
                    <button type="button" name="scheduled" class="btn btn-success btn-submit d-none" onclick="submitFrom('scheduled', 'Are you sure to schedule?')">Schedule</button>
                    <span class="ps-1"></span>
                    <button type="button" name="save" class="btn btn-secondary btn-submit d-none" onclick="submitFrom('save', 'Are you sure to save as draft?')">Save</button>`
    },
    keyboardSettings: {
        keyNavigation: false,
    },
    anchor: {
        enableNavigation: true,
        enableNavigationAlways: false,
        enableDoneState: true,
        markPreviousStepsAsDone: true,
        unDoneOnBackNavigation: false,
        enableDoneStateNavigation: true
    },
    disabledSteps: [],
    errorSteps: [],
    hiddenSteps: [],
    getContent: provideContent
});


    $("#state_selector").on("change", function() {
      $('#smartwizard').smartWizard("setState", [$('#step_to_style').val()], $(this).val(), !$('#is_reset').prop("checked"));
      return true;
    });

    $("#style_selector").on("change", function() {
      $('#smartwizard').smartWizard("setStyle", [$('#step_to_style').val()], $(this).val(), !$('#is_reset').prop("checked"));
      return true;
    });

  });

$("#smartwizard").on("leaveStep", function (e, anchorObject, currentStepIndex, nextStepIndex) {
// Display submit button on the final step
  if (nextStepIndex === 3) {
    $(".btn-submit").removeClass('d-none');
  } else {
    $(".btn-submit").addClass('d-none');
  }

    if (currentStepIndex === 0) { // Validate only on Step 0
        let form = document.getElementById("frm-schedule");

        const listDropdown = document.getElementById("list_ids");
        const choicesContainerList = listDropdown.closest('.choices'); // Get Choices.js container
        const sendingServerDropdown = document.getElementById("sending_server_ids");
        const choicesContainerSendingServer = sendingServerDropdown.closest('.choices'); // Get Choices.js container

        // Force form validation
        if (form.checkValidity() === false) {
            e.preventDefault(); // Prevent SmartWizard navigation
            form.classList.add("was-validated"); // Add Bootstrap validation styles

            if (!listDropdown.checkValidity()) {
                choicesContainerList.classList.add("is-invalid"); // Add red border
            } else {
                choicesContainerList.classList.remove("is-invalid"); // Remove red border
                choicesContainerList.classList.add("is-valid"); // Optionally add green border
            }

          
            if (!sendingServerDropdown.checkValidity()) {
                choicesContainerSendingServer.classList.add("is-invalid"); // Add red border
            } else {
                choicesContainerSendingServer.classList.remove("is-invalid"); // Remove red border
                choicesContainerSendingServer.classList.add("is-valid"); // Optionally add green border
            }

            return false; // Stop navigation
        } else {
          choicesContainerList.classList.remove("is-invalid"); // Remove red border
          choicesContainerSendingServer.classList.remove("is-invalid"); // Remove red border
        }
    }
    return true; // Allow navigation if valid
});