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

class Buttons {
    constructor()
    {
        this.initButtons();
    }

    get getButtonsHTML()
    {
        let html = `
            <button class="page-title-action flex-button ssgs-btn-outside" id="syncOnGoogleSheet">${wp.i18n.__('Sync on Google Sheet', 'stock-sync-with-google-sheet-for-woocommerce')}</button>
            `;

        if (!ssgsw_script.is_license_valid) {
            html += `
            <button class="page-title-action ssgsw-promo ssgsw-ultimate-button">${wp.i18n.__('Get Ultimate', 'stock-sync-with-google-sheet-for-woocommerce')}</button>
                `;
        }

        return html;
    }
    get getVendorButtonsHTML()
    {
        let html = ``;

        if (ssgsw_script.another_license) {
            html += `<a  style="padding-right:7px; font-weight:600" id="syncOnGoogleSheet" class="add_new_wcfm_ele_dashboard  page-title-action flex-button ssgs-btn-outside" href="#" ><span class="dashicons dashicons-update"></span>${wp.i18n.__('Sync on Google Sheet', 'stock-sync-with-google-sheet-for-woocommerce')}</a>`;
        }
        return html;
    }
    get getDokanVendorButtonsHTML(){
        let html = ``;

        if (ssgsw_script.another_license) {
            html += `<a  style="padding-right:7px; font-weight:600" id="syncOnGoogleSheet" class="dokan-btn dokan-btn-theme ssgs-btn-outside" href="#" ><span class="dashicons dashicons-update"></span>${wp.i18n.__('Sync on Google Sheet', 'stock-sync-with-google-sheet-for-woocommerce')}</a>`;
        }
        return html;
    }
    /**
     * Init buttons
     */
    initButtons()
    {
        const currentScreen = ssgsw_script.currentScreen;

        if (currentScreen.post_type === "product") {
            this.initProductsButtons();

            this.initEvents();
        } else {
          this.initVendorProductsButtons();
          
            this.initEvents();
            this.initVendorNewTag();
        }
       if (!ssgsw_script.vendor_page) {
          if (ssgsw_script.ssgsw_license_trigger) {
            const spinnerUrl = `${ssgsw_script.site_url}/wp-admin/images/spinner.gif`;
      
            Vn.fire({
              position: "center",
              timeout: false,
              icon: "info",
              title: wp.i18n.__("Product sync to 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;" />
                  <strong>${wp.i18n.__("Syncing data to the sheet.", "stock-sync-with-google-sheet-for-woocommerce")}</strong>
                </div>
              `,
            });
      
            this.syncOnGoogleSheet();
          }
       }
       
    }

    initProductsButtons()
    {
        const wpHeadEnd = document.querySelector(".wp-header-end");

        if (wpHeadEnd) {
            // insert before
            wpHeadEnd.insertAdjacentHTML("beforebegin", this.getButtonsHTML);
        }

        return true;
    }
    initVendorProductsButtons()
    {
        const wpHeadEnd = document.querySelector("#add_new_product_dashboard");
        const dokan_button = document.querySelector(".dokan-add-product-link"); 
        console.log(dokan_button);
                console.log('test_laod');
        if (wpHeadEnd) {
            // insert before
            wpHeadEnd.insertAdjacentHTML("afterend", this.getVendorButtonsHTML);
        }
        if (dokan_button) {
            // insert before
            dokan_button.insertAdjacentHTML("beforeend", this.getDokanVendorButtonsHTML);
        }
        

        return true;
    }
    initVendorNewTag()
    {
        const wpHeadEnd = document.querySelector(".wcfm_menu_flexstock .wcfm_menu_item");

        if (wpHeadEnd) {
            // insert before
            const newSpan = document.createElement('span');
            newSpan.style.color = '#065f46';
            newSpan.style.background = '#D1FAE5';
            newSpan.style.paddingLeft = '5px';
            newSpan.style.paddingRight = '5px';
            newSpan.style.fontSize = '13px';
            newSpan.style.borderRadius = '10px';
            newSpan.style.fontWeight = '600';
            newSpan.style.lineHeight = '23px';
            newSpan.textContent = wp.i18n.__('New', 'stock-sync-with-google-sheet-for-woocommerce');
            wpHeadEnd.append(newSpan);
        }

        return true;
    }
    /**
     * Init events
     */
    initEvents()
    {
        const events = {
            syncOnGoogleSheet: this.syncOnGoogleSheet,
            displayPromo: this.displayPromo,
        };

        for (let event in events) {
            const button = document.querySelector("#" + event);

            if (button) {
                button.addEventListener("click", events[event]);
            }
        }
    }

    /**
     * Sync on Google Sheet
     */
    async syncOnGoogleSheet(event){
        try {

         
            if (event) {
              event.preventDefault();
              event.stopPropagation();
            }
            
            console.log("Sync on Google Sheet");
      
            const spinnerUrl = `${ssgsw_script.site_url}/wp-admin/images/spinner.gif`;
            const syncButton = document.querySelector("#syncOnGoogleSheet");
      
            if (event) {
              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_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);
              }
             
              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.success(wp.i18n.__("Synced all products from all sites to Google Sheet!", "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 {
            const syncButton = document.querySelector("#syncOnGoogleSheet");
            if (syncButton) {
                syncButton.innerHTML = wp.i18n.__("Sync on Google Sheet", "stock-sync-with-google-sheet-for-woocommerce");
                syncButton.classList.remove("disabled");
            }
            const attr_value = syncButton.getAttribute('data_attr');
            if (attr_value == 'vendor_sync') {
                location.reload();
            }
        }
    }
}

export default Buttons;
