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">Sync orders on Google Sheet</button>
            `;

    if (!osgsw_script.is_ultimate_license_activated) {
      html += `
      <button class="page-title-action osgsw-promo osgsw-ultimate-button">Get Ultimate</button>
                `;
    }

    return html;
  }

  /**
   * Init buttons
   */
  initButtons() {
    const currentScreen = osgsw_script.currentScreen;
    const ssgsw_page_name = osgsw_script.page_name;
    console.log(ssgsw_page_name);
    if (currentScreen.post_type === "shop_order" || ssgsw_page_name == 'wc-orders') {
      this.initOrdersButtons();

      this.initEvents();
    }
    if (osgsw_script.osgsw_license_trigger) {
          const spinnerUrl = `${osgsw_script.site_url}/wp-admin/images/spinner.gif`;
          Vn.fire({
            position: "center",
            timeout: false,
            icon: "info",
            title: "Order sync to sheet",
            content: `
              <div class="ssgsw_progress_bar_wrap">
                <img src="${spinnerUrl}" alt="Loading..." style="margin-top: -5px; margin-right: 2px;" />
                <strong>Syncing data to the sheet.</strong>
              </div>
            `,
          });
    
          this.syncOnGoogleSheet();
       }

  }

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

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

    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]);
      }
    }
  }
  
  async syncOnGoogleSheet(event){
      try {
          if (event) {
            event.preventDefault();
            event.stopPropagation();
          }
    
          console.log("Sync on Google Sheet");
    
          const spinnerUrl = `${osgsw_script.site_url}/wp-admin/images/spinner.gif`;
          const syncButton = document.querySelector("#syncOnGoogleSheet");
    
          if (event) {
            syncButton.innerHTML = `
              <div>
                <img src="${spinnerUrl}" alt="Loading..." /> Syncing...
              </div>
            `;
            syncButton.classList.add("disabled");
          }
    
          // Initial sync request
          const syncResponse = await Ajax.post("osgsw_sync_sheet");
    
          let successCount = 0;
          let errorCount = 0;

    
          if (syncResponse.success) {
            const batchSize = 1500;
            const totalItems = syncResponse.message;
    
            let offset = 0;
            while (offset < totalItems) {
              // Fix: Add isLastBatch flag for manual sync buttons
              const isLastBatch = (offset + batchSize) >= totalItems;
              const batchResponse = await Ajax.post("osgsw_sync_batch_to_sheet", {
                offset,
                batchSize,
                isLastBatch, 
              });
    
              if (batchResponse.success) {
                const progress = (((offset + batchSize) / totalItems) * 100).toFixed(2);
                successCount++;
    
                Vn.fire({
                  position: "center",
                  timeout: false,
                  icon: "info",
                  title: "Syncing Orders to Google Sheet",
                  content: `
                    <div class="ssgsw_progress_bar_wrap">
                      <img src="${spinnerUrl}" alt="Loading..." style="margin-top: -5px; margin-right: 2px;" />
                      <progress id="ssgsw_progress_bar_3" value="${progress}" max="100"></progress>
                      <strong style="margin-left: 3px; margin-top: -2px">${progress}%</strong>
                    </div>
                    <p style="text-align: center"><strong>Please wait...</strong></p>
                  `,
                });
    
                offset += batchSize;
              } else {
                errorCount++;
                if (errorCount > 5) {
                  offset += batchSize;
                }
              }
            }
    
            // Handle completion messages
            if (successCount > 0) {
              Vn.success("Synced on Google Sheet!");
            } else {
              Vn.error("Error: Sync failed!");
            }
          } else {
            Vn.fire({
              position: "center",
              timeout: false,
              icon: "warning",
              content: syncResponse.message,
            });
          }
      } catch (error) {
          console.error("Error during sync:", error);
          Vn.error("Unexpected error occurred!");
      } finally {
          const syncButton = document.querySelector("#syncOnGoogleSheet");
          if (syncButton) {
            syncButton.innerHTML = "Sync on Google Sheet";
            syncButton.classList.remove("disabled");
          }
      }
  }
}

export default Buttons;
