import { Ajax, Vn, Toast, isTrue } from "./helper";

const Dashboard = {
  state: {
    currentTab: "dashboard",
  },
  syncSetting: {
    syncMode: ssgsw_script.options.selected_sync_mode,
    ['live-sync']: {
      syncDirection: ssgsw_script.options.live_sync_direction,
    },
    ['perodic-sync']: {
      syncDirection: ssgsw_script.options.peroidic_sync_direction,
    }
  },
  option: {},
  syncMode: ssgsw_script.options.multi_store_mode_on || 'shop_to_sheet',

  show_disable_popup: false,
  connectedSites: ssgsw_script.multi_store_list || [{ url: '', token: '', isConnected: false }],
  connectedSitesParent: ssgsw_script.multi_store_list_parent || [],
  confirmingIndex: null,
  show_multi_disable_popup1: false,
  setting_tab2: 1,
  show_multi_disable_popup: false,
  show_multi_setting_rename: false,
  write_text2: false,
  write_text3: false,
  show_multi_inactive: false,
  write_text: false,
  show_discrad: false,
  save_change: 0,
  show_notice_popup_setup: false,
  isLoading: false,
  hovered: false,
  setting_view: false,
  setting_tab: false,
  write_text2: false,
  write_text3: false,
  popupVisible: false,
  copied: false,
  show_vendor_popup: false,
  productTypes: ssgsw_script.product_type,
  statusOptions: ssgsw_script.product_status,
  categoryOptions: ssgsw_script.product_category,

  filters: ssgsw_script.all_filter,
  siteAttributes: ssgsw_script.site_attributes,
  ssgsw_copyText: function (elementId) {
    let inputElement = document.getElementById(elementId);
    inputElement.select();
    inputElement.setSelectionRange(0, 99999); // For mobile devices

    try {
      document.execCommand('copy');
      Vn.fire({
        title: wp.i18n.__("Text copied to clipboard!", "stock-sync-with-google-sheet-for-woocommerce"),
        icon: "success",
      });
    } catch (err) {
      Vn.fire({
        title: wp.i18n.__("Failed to copy text.", "stock-sync-with-google-sheet-for-woocommerce"),
        icon: "error",
      });
    }
  },
  confirmRemove(index) {
    console.log(index);
    // When the main button is clicked, set the index to show the popup
    this.confirmingIndex = index;
  },
  SyncButton() {
    return this.syncMode == 'shop_to_sheet';
  },
  SyncButton2() {
    return this.syncMode == 'multi_to_single';
  },
  addFilter() {
    this.filters.push({ field: 'post_status', operator: 'equals', value: 'Published' });
  },
  removeFilter(index) {
    if (this.filters.length > 1) {
      this.filters.splice(index, 1);
    }
  },
  onFieldChange(index) {
    // Reset value when field changes
    const field = this.filters[index].field;
    let defaultValue = null; // Default to null if not predefined

    if (field === 'post_status') {
      defaultValue = 'publish'; // Default value for post_status
    } else if (field === 'category') {
      defaultValue = Object.keys(this.categoryOptions)[0];
    } else if (field === 'post_type') {
      defaultValue = Object.keys(this.productTypes)[0];
    }
    this.filters[index].value = defaultValue;
  },
  preventDefault: (event) => { event.preventDefault() },
  copyEmail() {
    const button = document.querySelector(".support-button");
    const email = button.getAttribute("data-email");

    // Copy the email to the clipboard
    const tempInput = document.createElement("input");
    tempInput.value = email;
    document.body.appendChild(tempInput);
    tempInput.select(); +
      document.execCommand("copy");
    document.body.removeChild(tempInput);

    this.copied = true;
    if (this.copied) {
      button.classList.add("copy");
    }
    setTimeout(() => {
      this.copied = false;
      button.classList.remove("copy");
    }, 1000);
  },
  get limit() {
    return ssgsw_script.limit;
  },
  get vendorInactive() {
    return ssgsw_script.multi_vendor_inactive;
  },
  get isPro() {
    return ssgsw_script.is_license_valid;
  }, get isMultiStoreActive() {
    return ssgsw_script.is_multistore_activate;
  },
  get isMultiStoreInstalled() {
    return ssgsw_script.is_multistore_installed;
  },
  get isVendorActive() {
    return ssgsw_script.vendor_active;
  },
  get isMultiStoreActive() {
    return ssgsw_script.is_multistore_activate;
  },
  get isMultiStoreInstalled() {
    return ssgsw_script.is_multistore_installed;
  },
  get vendorLicenseActive() {
    return ssgsw_script.another_license;
  },
  get isVendorInstall() {
    return ssgsw_script.multi_vendor_install;
  },

  get isReady() {
    return ssgsw_script.is_plugin_ready;
  },
  get isVendorRequest() {
    return ssgsw_script.vendor_request;
  },
  isHovered() {
    return {
      hovered: false,
      toggleHovered() {
        this.hovered = !this.hovered;
      },
    };
  },

  togglePopup() {
    this.popupVisible = !this.popupVisible;
    if (this.popupVisible) {
      document.body.classList.add("popup-open");
    } else {
      document.body.classList.remove("popup-open");
    }
  },

  /**
   * forUltimate
   */

  get forUltimate() {
    return this.isPro == true ? "" : "ssgsw-promo";
  },
  get forVendor() {
    return this.vendorLicenseActive == true ? "" : "";
  },
  toggleSelectAllAttributes() {
    if (this.isAllAttributesSelected) {
      // If all are currently selected, we want to skip them all (deselect all)
      this.option.skipped_attributes = this.siteAttributes.map(attr => attr.slug);
    } else {
      // If some are not selected, select them all (clear skipped list)
      this.option.skipped_attributes = [];
    }
    this.save_change++;
  },
  get isAllAttributesSelected() {
    if (!this.option.skipped_attributes) return true;
    return this.option.skipped_attributes.length === 0;
  },
  init() {
    this.option = ssgsw_script.options || {};
    this.syncTabWithHash();
    this.initHeadway();
    this.select2Alpine();
    this.initProSelect2();
    this.select2Alpine_status();
    this.updateSettingTabFromHash();
    this.updateSettingTabFromHash2();
    console.log(ssgsw_script.is_license_valid);
  },
  initProSelect2() {
    jQuery(document).ready(function ($) {
      // Initialize the Select2 dropdown
      $('#ssgsw-pro-select').select2({
        minimumResultsForSearch: Infinity,
        templateResult: function (data, container) {
          var isPro = $(data.element).attr('data-pro-feature');
          if (isPro) {
            $(container).addClass('ssgsw_pro_option');
          }
          return data.text;
        }
      });

      // Add an event listener for when the user selects a new option
      $('#ssgsw-pro-select').on('change', function () {
        // Get the selected option element
        const selectedOption = $(this).find(':selected');

        // Check if the selected option has the 'data-pro-feature' attribute
        if (selectedOption.attr('data-pro-feature')) {
          // If it's a Pro feature, show the popup
          WPPOOL.Popup('stock_sync_with_google_sheet_for_woocommerce').show();
        }
        $('#ssgsw-pro-select').val('10').trigger('change');
      });
    });
  },
  reload_the_page() {
    window.location.reload();
  },
  updateSettingTabFromHash2() {
    if (window.location.hash === '#license') {
      this.setting_tab2 = 3;
    } else {
      this.setting_tab2 = 1; // Or whatever default behavior you need
    }
  },
  updateSettingTabFromHash() {
    if (window.location.hash === '#license') {
      this.setting_tab = true;
    } else {
      this.setting_tab = false; // Or whatever default behavior you need
    }
  },
  initHeadway() {
    let scriptURL = "//cdn.headwayapp.co/widget.js";
    let headway = document.createElement("script");
    headway.src = scriptURL;
    headway.async = true;
    document.body.appendChild(headway);

    // on load
    headway.onload = function () {
      let config = {
        selector: "#ssgsw_changelogs", // CSS selector where to inject the badge
        account: "7g2gGx",
        trigger: ".ssgsw_changelogs_trigger", // Trigger to show the badge
      };
      Headway.init(config);
    };
  },

  isTab(tab = "dashboard") {
    return this.state.currentTab === tab;
  },

  setTab(tab) {
    // Update the URL hash and state
    window.location.hash = tab;
    this.state.currentTab = tab;
    if (!ssgsw_script.vendor_page) {
      // Selectors for Dashboard and Settings links
      const dashboardLink = document.querySelector('#toplevel_page_ssgsw-admin ul li.wp-first-item');
      const settingsLink = document.querySelector('.toplevel_page_ssgsw-admin a[href="admin.php?page=ssgsw-admin&tab=settings"]');
      dashboardLink.classList.remove('current');
      settingsLink.closest('li').classList.remove('current');
      // Remove the "current" class from both links initially

      // Add the "current" class to the appropriate tab
      if (tab === 'dashboard') {
        dashboardLink.classList.add('current'); // Add "current" class to Dashboard link
      } else if (tab === 'settings') {
        settingsLink.closest('li').classList.add('current'); // Add "current" class to Settings parent <li>
      }
    }
  },

  syncTabWithHash() {
    let hash = window.location.hash;

    if (hash === "") {
      hash = "dashboard";
    } else {
      hash = hash.replace("#", "");
    }

    this.state.currentTab = hash;
    if (!ssgsw_script.vendor_page) {
      const settingsLink = document.querySelector('.toplevel_page_ssgsw-admin a[href="admin.php?page=ssgsw-admin&tab=settings"]');
      if (hash == 'settings') {
        settingsLink.closest('li').classList.add('current');
      }
    }
  },
  async performRemove(index, remove_key = 'parent') {
    if ('parent' === remove_key) {
      var site = this.connectedSitesParent[index];
      var action = 'remove_child';
    } else {
      var site = this.connectedSites[index];
      var action = 'remove_parent';
    }

    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_site_remove", {
        options: {
          site: site,
          action: action
        }
      });
      if (updateResponse.success) {
        if ('parent' == remove_key) {
          this.connectedSitesParent.splice(index, 1);
        } else {
          this.connectedSites.splice(index, 1);
        }


        Vn.fire({
          title: wp.i18n.__("Your setting remove successfully!", "stock-sync-with-google-sheet-for-woocommerce"),
          icon: "success",
        });
      } else {
        Vn.fire({
          icon: "error",
          title: wp.i18n.__("Error remove to site.", "stock-sync-with-google-sheet-for-woocommerce"),
        });

      }
    } catch (error) {
      console.error("Error connecting to site.:", error);
      Vn.fire({
        icon: "error",
        title: wp.i18n.__("Error connecting to site.", "stock-sync-with-google-sheet-for-woocommerce"),
      });
    }
    this.confirmingIndex = null;
    location.reload();
  },
  async SyncChildShop(sites, event) {
    const syncButton = event.currentTarget; // This is the key change!
    const originalContent = syncButton.innerHTML;
    const spinnerUrl = `${ssgsw_script.site_url}/wp-admin/images/spinner.gif`;
    try {
      // Set the button to a loading state
      syncButton.innerHTML = `
      <div>
        <img src="${spinnerUrl}" alt="${wp.i18n.__("Loading...", "stock-sync-with-google-sheet-for-woocommerce")}" /> ${wp.i18n.__("Syncing...", "stock-sync-with-google-sheet-for-woocommerce")}
      </div>
    `;
      syncButton.classList.add("disabled");

      // Initial sync request
      const syncResponse = await Ajax.post("ssgsw_fetch_sku_product");

      if (syncResponse) {
        let totalSyncedProducts = 0;
        let indexNumber = 1;
        let totalProgress = 0;
        const batchSize = 250;

        // Loop through each site in the response.
        const siteUrl = sites.url;
        const siteToken = sites.token;
        const totalItems = parseInt(syncResponse.message);
        console.log(totalItems);
        let offset = 0;
        while (offset < totalItems) {
          const batchResponse = await Ajax.post("ssgsw_marge_sub_site", {
            offset,
            batchSize,
            index_number: indexNumber,
            site_url: siteUrl,
            site_token: siteToken
          });
          console.log(batchResponse);

          if (batchResponse.success) {
            totalSyncedProducts += batchResponse.data.count;
            // Update total progress based on all sites
            const currentProgress = (totalSyncedProducts / totalItems) * 100;
            totalProgress = currentProgress.toFixed(2);
            let progress_notice = 100;
            if (totalProgress < progress_notice) {
              progress_notice = totalProgress;
            }
            Vn.fire({
              position: "center",
              timeout: false,
              icon: "info",
              title: wp.i18n.__("Syncing Products to ", "stock-sync-with-google-sheet-for-woocommerce") + siteUrl,
              content: `
                <div class="ssgsw_progress_bar_wrap">
                  <img src="${spinnerUrl}" alt="${wp.i18n.__("Loading...", "stock-sync-with-google-sheet-for-woocommerce")}" style="margin-top: -5px; margin-right: 2px;" />
                  <progress id="ssgsw_progress_bar_3" value="${totalProgress}" max="100"></progress>
                  <strong style="margin-left: 3px; margin-top: -2px">${progress_notice}%</strong>
                </div>
                <p style="text-align: center"><strong>${wp.i18n.__("Please wait...", "stock-sync-with-google-sheet-for-woocommerce")}</strong></p>
              `,
            });
            offset += batchSize;
          } else {
            // Handle batch error
            Vn.error(wp.i18n.__("Error syncing batch from ", "stock-sync-with-google-sheet-for-woocommerce") + siteUrl + ": " + batchResponse.message);
            break; // Stop syncing this site's products on error
          }
        }
        // Handle completion messages after all sites have been processed
        if (totalSyncedProducts > 0) {
          Vn.success(wp.i18n.__("Sync product to ", "stock-sync-with-google-sheet-for-woocommerce") + siteUrl + wp.i18n.__(" Successfully!", "stock-sync-with-google-sheet-for-woocommerce"));
        } else {
          Vn.error(wp.i18n.__("Error: No products were synced from any site.", "stock-sync-with-google-sheet-for-woocommerce"));
        }
      } else {
        Vn.fire({
          position: "center",
          timeout: false,
          icon: "warning",
          content: syncResponse.message,
        });
      }
    } catch (error) {
      console.error("Error during sync:", error);
      Vn.error(wp.i18n.__("Unexpected error occurred!", "stock-sync-with-google-sheet-for-woocommerce"));
    } finally {
      // Restore the button to its original state, regardless of success or failure.
      syncButton.innerHTML = originalContent;
      syncButton.classList.remove("disabled");
    }
  },
  async ChangeMode(value) {
    console.log(value);
    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_mode_change", {
        options: {
          ssgsw_mode: value,
        }
      });
      if (updateResponse.success) {

        this.syncMode = value;

        Vn.fire({
          title: wp.i18n.__("Great, your mode change successfully!", "stock-sync-with-google-sheet-for-woocommerce"),
          icon: "success",
        });

      } else {
        Vn.fire({
          icon: "error",
          title: wp.i18n.__("Error change mode.", "stock-sync-with-google-sheet-for-woocommerce"),
        });

      }
    } catch (error) {
      console.error("Error connecting to site.:", error);
      Vn.fire({
        icon: "error",
        title: wp.i18n.__("Error change mode.", "stock-sync-with-google-sheet-for-woocommerce"),
      });
    }

  },
  async ssgsw_connectSite(site) {
    console.log(site);
    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_request_for_connect", {
        options: {
          child_site: site,
        }
      });
      if (updateResponse.success) {
        Vn.fire({
          title: wp.i18n.__("Great, your site connection successfully!", "stock-sync-with-google-sheet-for-woocommerce"),
          icon: "success",
        });
        site.isConnected = true;
      } else {
        Vn.fire({
          icon: "error",
          title: wp.i18n.__("Error connecting to site.", "stock-sync-with-google-sheet-for-woocommerce"),
        });
        site.isConnected = false;
      }
    } catch (error) {
      console.error("Error connecting to site.:", error);
      Vn.fire({
        icon: "error",
        title: wp.i18n.__("Error connecting to site.", "stock-sync-with-google-sheet-for-woocommerce"),
      });
      site.isConnected = false;
    }

  },
  async save_multistore_settings(key = "") {
    const e = this; // Reference to the current object
    console.log(this.connectedSitesParent);

    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_multistore_setting", {
        options: {
          multi_store_active: e.option.multi_store_active,
          multi_store_mode_on: this.syncMode,
          multi_connect_mode_on: e.option.multi_connect_mode_on,
          multi_store_list_parent: this.connectedSitesParent,
          multi_store_list: this.connectedSites
        }
      });
      if (updateResponse.success) {
        Vn.fire({
          title: wp.i18n.__("Great, your settings are saved!", "stock-sync-with-google-sheet-for-woocommerce"),
          icon: "success",
        });
      }
    } catch (error) {
      console.error("Error while saving settings:", error);
      Vn.fire({
        icon: "error",
        title: wp.i18n.__("Unexpected error occurred!", "stock-sync-with-google-sheet-for-woocommerce"),
      });
    } finally {
      e.isLoading = false;
    }

  },
  async save_multi_vendor_settings(key = "") {
    const e = this; // Reference to the current object

    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_update_vendor_setting", {
        options: {
          multi_vendor_active: e.option.multi_vendor_active,
          vendor_menu_name: e.option.vendor_menu_name,
          vendor_active_instance: e.option.vendor_active_instance,
          product_sync_cron: e.option.product_sync_cron,
          cron_sync_day: e.option.cron_sync_day,
          sync_time: e.option.sync_time,

        }
      });
      if (updateResponse.success) {
        Vn.fire({
          title: wp.i18n.__("Great, your settings are saved!", "stock-sync-with-google-sheet-for-woocommerce"),
          icon: "success",
        });
      }
    } catch (error) {
      console.error("Error while saving settings:", error);
      Vn.fire({
        icon: "error",
        title: wp.i18n.__("Unexpected error occurred!", "stock-sync-with-google-sheet-for-woocommerce"),
      });
    } finally {
      e.isLoading = false;
    }

  },
  /**
   * Update Dashboard Settings
   */

  async save_checkbox_settings(key = "") {
    const e = this; // Reference to the current object
    var sync_mode = this.syncSetting.syncMode;
    var live_direction = this.syncSetting['live-sync'].syncDirection;
    var perodic_direction = this.syncSetting['perodic-sync'].syncDirection;
    // Toggle save_and_sync option
    e.option.save_and_sync = !e.option.save_and_sync;

    try {
      // Update options on the server
      const updateResponse = await Ajax.post("ssgsw_update_options", {
        options: {
          add_products_from_sheet: e.option.add_products_from_sheet,
          show_sku: e.option.show_sku,
          show_short_description: e.option.show_short_description,
          show_attributes: e.option.show_attributes,
          show_total_sales: e.option.show_total_sales,
          show_product_category: e.option.show_product_category,
          show_custom_meta_fileds: e.option.show_custom_meta_fileds,
          show_custom_fileds: e.option.show_custom_fileds,
          show_product_images: e.option.show_product_images,
          bulk_edit_option: e.option.bulk_edit_option,
          formula_active: e.option.formula_active,
          show_product_url: e.option.show_product_url,
          show_long_description: e.option.show_long_description,
          show_product_status: e.option.show_product_status,
          show_product_status_data: e.option.show_product_status_data,
          show_product_tags: e.option.show_product_tags,
          show_product_image_alt: e.option.show_product_image_alt,
          show_upsell_ids: e.option.show_upsell_ids,
          show_crosssell_ids: e.option.show_crosssell_ids,
          show_custom_badge: e.option.show_custom_badge,
          show_product_brand: e.option.show_product_brand,
          all_product_filter_info: this.filters,
          filter_active: e.option.filter_active,
          shop_name_sync: e.option.shop_name_sync,
          separate_attributes: e.option.separate_attributes,
          allowed_attributes: e.option.allowed_attributes,
          skipped_attributes: e.option.skipped_attributes,
          selected_sync_mode: sync_mode,
          live_sync_direction: live_direction,
          peroidic_sync_direction: perodic_direction,
          cron_perdic_sync: e.option.cron_perdic_sync,
          cron_formula_perdic_sync: e.option.cron_formula_perdic_sync,
          perdic_sync_day: e.option.perdic_sync_day,
          perdic_formula_sync_day: e.option.perdic_formula_sync_day,
          perdic_sync_time: e.option.perdic_sync_time,
          perdic_formula_sync_time: e.option.perdic_formula_sync_time,
          save_and_sync: e.option.save_and_sync,
        },
      });

      const spinnerUrl = `${ssgsw_script.site_url}/wp-admin/images/spinner.gif`;

      // Handle update response
      if (!updateResponse.success) {
        Vn.fire({
          icon: "error",
          title: wp.i18n.__("Oops, settings save failed!", "stock-sync-with-google-sheet-for-woocommerce"),
        });
        return;
      }

      const syncResponse = await Ajax.post("ssgsw_sync_sheet");
      if (syncResponse.success) {
        let totalSyncedProducts = 0;
        let totalProductsAcrossAllSites = 0;
        let indexNumber = 1;

        // First, calculate the total product count across all sites.
        for (const site of syncResponse.data) {
          totalProductsAcrossAllSites += parseInt(site.product, 10);
        }
        console.log(totalProductsAcrossAllSites);
        let totalProgress = 0;
        const batchSize = 1000;

        // Loop through each site in the response.
        for (const site of syncResponse.data) {
          const siteUrl = site.url;
          const siteToken = site.token;
          const totalItems = parseInt(site.product, 10);


          let offset = 0;
          while (offset < totalItems) {
            const batchResponse = await Ajax.post("ssgsw_sync_batch_to_sheet", {
              offset,
              batchSize,
              index_number: indexNumber,
              site_url: siteUrl,
              site_token: siteToken
            });

            if (batchResponse.success) {
              totalSyncedProducts += batchResponse.data.count;
              indexNumber += batchResponse.data.count;

              // Update total progress based on all sites
              const currentProgress = (totalSyncedProducts / totalProductsAcrossAllSites) * 100;
              totalProgress = currentProgress.toFixed(2);
              var progress_notice = 100;
              if (totalProgress < progress_notice) {
                progress_notice = totalProgress;
              }

              Vn.fire({
                position: "center",
                timeout: false,
                icon: "info",
                title: wp.i18n.__("Syncing Products to Google Sheet", "stock-sync-with-google-sheet-for-woocommerce"),
                content: `
                                  <div class="ssgsw_progress_bar_wrap">
                                      <img src="${spinnerUrl}" alt="${wp.i18n.__("Loading...", "stock-sync-with-google-sheet-for-woocommerce")}" style="margin-top: -5px; margin-right: 2px;" />
                                      <progress id="ssgsw_progress_bar_3" value="${totalProgress}" max="100"></progress>
                                      <strong style="margin-left: 3px; margin-top: -2px">${progress_notice}%</strong>
                                  </div>
                                  <p style="text-align: center"><strong>${wp.i18n.__("Please wait...", "stock-sync-with-google-sheet-for-woocommerce")}</strong></p>
                              `,
              });
              offset += batchSize;
            } else {
              // Handle batch error
              Vn.error(wp.i18n.sprintf(wp.i18n.__('Error syncing batch from %s: %s', 'stock-sync-with-google-sheet-for-woocommerce'), siteUrl, batchResponse.message));
              break; // Stop syncing this site's products on error
            }
          }
        }
        // Handle completion messages after all sites have been processed
        if (totalSyncedProducts > 0) {
          Vn.fire({
            title: wp.i18n.__("Great, your settings are saved!", "stock-sync-with-google-sheet-for-woocommerce"),
            icon: "success",
          });
        } else {
          Vn.error(wp.i18n.__("Error: No products were synced from any site.", "stock-sync-with-google-sheet-for-woocommerce"));
        }
      } else {
        var rest_sheet = await Ajax.post("ssgsw_reset_sheet_setting");
        Vn.fire({
          icon: "warning",
          title: wp.i18n.__('Your settings have been saved successfully, but no products were found to sync at this time.', 'stock-sync-with-google-sheet-for-woocommerce'),
        });

      }
    } catch (error) {
      console.error("Error during sync:", error);
      Vn.error(wp.i18n.__("Unexpected error occurred!", "stock-sync-with-google-sheet-for-woocommerce"));
    } finally {
      e.isLoading = false;
      e.save_change = false;
    }

  },
  /**
   * init select2
   */
  select2Alpine() {
    var select2_alpine = jQuery(this.$refs.select).select2({
      placeholder: wp.i18n.__("Enter your product's custom filed (metadata)", "stock-sync-with-google-sheet-for-woocommerce"),
      allowClear: true,
      width: "90%",
      css: {
        "font-size": "16px" /* Adjust the font size as desired */,
      },
      templateResult: function (option) {
        if (option.disabled) {
          var text_value = option.text;
          if (
            text_value ==
            "(Custom field with reserved words are not supported yet)"
          ) {
            return jQuery(
              "<span>" +
              option.id +
              '<span class="ssgsw_disabled-option"> ' + wp.i18n.__("(Custom field with reserved words are not supported yet)", "stock-sync-with-google-sheet-for-woocommerce") + "</span></span>"
            );
          } else {
            return jQuery(
              "<span>" +
              option.text +
              '<span class="ssgsw_disabled-option"> ' + wp.i18n.__("(This field type is not supported yet)", "stock-sync-with-google-sheet-for-woocommerce") + "</span></span>"
            );
          }
        }
        return option.text;
      },
    });
    select2_alpine.on("select2:select", (event) => {
      this.option.show_custom_fileds = jQuery(event.target).val();
      this.save_change = true;
    });
    select2_alpine.on("select2:unselect", (event) => {
      this.option.show_custom_fileds = jQuery(event.target).val();
      this.save_change = true;
    });
  },
  /**
 * init select2
 */
  select2Alpine_status() {
    var select2_alpine2 = jQuery(this.$refs.show_product_status_info).select2({
      placeholder: wp.i18n.__("Enter your product's status", "stock-sync-with-google-sheet-for-woocommerce"),
      allowClear: false,
      width: "90%",
      css: {
        "font-size": "16px" /* Adjust the font size as desired */,
      },
      templateResult: function (option) {
        return option.text;
      },
    });
    select2_alpine2.on("select2:select", (event) => {
      this.option.show_product_status_data = jQuery(event.target).val();
      this.save_change = true;
    });
    select2_alpine2.on("select2:unselect", (event) => {
      this.option.show_product_status_data = jQuery(event.target).val();
      this.save_change = true;
    });
    let lastValidSelection = select2_alpine2.val();
    select2_alpine2.on("change", (event) => {
      var currentSelection = select2_alpine2.val();
      if (currentSelection === null || currentSelection.length === 0) {
        select2_alpine2.val(lastValidSelection).trigger("change");
        Vn.fire({
          position: "center",
          timeout: false,
          icon: "info",
          title: wp.i18n.__("You must keep at least one option selected. The last selection cannot be removed.", "stock-sync-with-google-sheet-for-woocommerce"),

        });
        return false;
      }
      lastValidSelection = currentSelection;
    });

  },
  get isSheetSelected() {
    let spreadsheet_url = this.option.spreadsheet_url,
      sheet_tab = this.option.sheet_tab;

    // validate spreadsheet_url valid URL
    if (spreadsheet_url && spreadsheet_url.length > 0) {
      try {
        let url = new URL(spreadsheet_url);
        if (url.protocol !== "https:" || url.hostname !== "docs.google.com") {
          return false;
        }
      } catch (e) {
        return false;
      }
    }

    // valid sheet name

    if (!sheet_tab) {
      return false;
    }

    return true;
  },

  /**
   * Change Setup
   */

  async changeSetup(event) {
    let response = await Ajax.post("ssgsw_update_options", {
      options: {
        setup_step: 2,
      },
    });

    // window.location.href = ssgsw_script.site_url + "/wp-admin/admin.php?page=ssgsw-admin";
    // console.log(ssgsw_script.setting_page_url);
    // window.location.href = ssgsw_script.setting_page_url;
    window.location.reload();
  },

  /**
   * toggleChangelogs
   */
  toggleChangelogs() {
    // click on HW_badge_cont
    // document.querySelector(".HW_badge_cont").click();
  },

  /**
   * Hide upgrade notice
   */
  async hideUpgradeNotice() {
    const notice = document.querySelector(".ssgsw-upgrade-notice");

    if (notice) {
      notice.style.display = "none";
    }

    let response = await Ajax.post("ssgsw_hide_upgrade_notice", {});

    console.log("re", response);
  },
};

export default () => Dashboard;
