import { showToast, serializeForm, filterEmptyRepeaterEntries } from './utils.js';
import { handleDependentMarkup } from './dependentMarkup.js';

const $daftplugAdmin = jQuery('#daftplugAdmin');

export function initSettings() {
  // Delay setup to avoid initial form population triggering saves
  setTimeout(() => {
    setupFormAutoSave();
  }, 1000);
}

// Debounce timer
let saveTimeout = null;

function setupFormAutoSave() {
  const form = $daftplugAdmin.find('form[name="settingsForm"]');

  // Prevent default form submission
  form.on('submit', function (e) {
    e.preventDefault();
  });

  // Save when input elements are changed
  form.on('change input paste', 'input, select, textarea', function (e) {
    const changedForm = jQuery(e.target).closest('form');
    triggerSaveSettings(changedForm);
  });
}

// Separate function that can be called programmatically to save settings
export function triggerSaveSettings(targetForm = null) {
  const form = targetForm || $daftplugAdmin.find('form[name="settingsForm"]');

  if (!form[0]) {
    console.error('No form element found!');
    return;
  }

  clearTimeout(saveTimeout);
  saveTimeout = setTimeout(() => {
    saveSettings(form);
  }, 500);
}

export async function saveSettings(form = null) {
  // This handles dynamic required fields based on other field states
  await new Promise((resolve) => setTimeout(resolve, 100));

  // Re-run dependent markup to ensure all dynamic states are current
  handleDependentMarkup();

  // Small additional delay to ensure DOM updates are complete
  await new Promise((resolve) => setTimeout(resolve, 50));

  // Validate the specific form before saving
  if (!form[0].checkValidity()) {
    form[0].reportValidity();
    return;
  }

  // Prevent multiple simultaneous saves
  if (form.attr('data-saving') === 'true') {
    return;
  }

  form.attr('data-saving', 'true');

  // Show loading toast
  const loadingToast = showToast(wp.i18n.__('Saving...', 'generatify'), wp.i18n.__('Changes are being saved.', 'generatify'), 'loading', 'top-right', false, false);

  try {
    // Prepare settings data
    const rawSettings = serializeForm(form[0]);
    // Filter out empty repeater entries to avoid saving empty fieldsets
    const parsedSettings = filterEmptyRepeaterEntries(rawSettings);

    // Save settings to server (WP REST)
    const response = await fetch(wpApiSettings.root + 'generatify/v1/settings', {
      method: 'PUT',
      headers: {
        'X-WP-Nonce': wpApiSettings.nonce,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        settings: parsedSettings,
      }),
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();

    if (data.status === 'success') {
      // Hide loading toast and show success message
      loadingToast.css('opacity', '0');
      setTimeout(() => loadingToast.remove(), 200);

      showToast(wp.i18n.__('Settings Saved', 'generatify'), wp.i18n.__('Changes have been saved.', 'generatify'), 'success', 'top-right', true, false);
    } else {
      // Hide loading toast before throwing error
      loadingToast.css('opacity', '0');
      setTimeout(() => loadingToast.remove(), 200);
      throw new Error('Save failed');
    }
  } catch (error) {
    console.error('Save failed:', error);

    // Hide loading toast and show error message
    loadingToast.css('opacity', '0');
    setTimeout(() => loadingToast.remove(), 200);

    showToast(wp.i18n.__('Save Failed', 'generatify'), wp.i18n.__('Changes have failed to be saved.', 'generatify'), 'fail', 'top-right', true, false);
  } finally {
    form.removeAttr('data-saving');
  }
}
