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

const Dashboard = {
  state: {
    currentTab: "dashboard",
  },
  option: {},

  show_disable_popup2: false,
  show_notice_popup: false,
  show_discrad: false,
  save_change: 0,
  osgs_default_state: false,
  isLoading: false,

  // show_discrad: false,
  reload_the_page() {
    window.location.reload();
  },
  get limit() {
    return osgsw_script.limit;
  },

  get isPro() {
    return osgsw_script.is_ultimate_license_activated;
  },

  get isReady() {
    return osgsw_script.is_plugin_ready;
  },

  /**
   * forUltimate
   */

  get forUltimate() {
    return this.isPro === true ? "" : "osgsw-promo";
  },

  init() {
    // console.log("Dashboard init", osgsw_script);
    this.option = osgsw_script.options || {};

    // Debug: Log all status-related options
    // console.log("Status options loaded:", this.getAllStatusOptions());

    this.syncTabWithHash();
    this.initHeadway();
    this.select2Alpine();
  },

  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 () {
      // console.log("headway loaded");

      let config = {
        selector: "#osgsw_changelogs", // CSS selector where to inject the badge
        account: "7kAVZy",
        trigger: ".osgsw_changelogs_trigger", // Trigger to show the badge
      };
      Headway.init(config);
    };
  },

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

  setTab(tab) {
    window.location.hash = tab;
    this.state.currentTab = tab;
  },

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

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

    this.state.currentTab = hash;
  },

  select2Alpine() {
    if (this.option.show_custom_fields) {
      this.selectedOrder = this.option.show_custom_fields;
    } else {
      this.selectedOrder = [];
    }

    var select2_alpine = jQuery(this.$refs.select).select2({
      placeholder: "Enter your product's custom field (metadata)",
      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"> (Custom field with reserved words are not supported yet)</span></span>'
            );
          } else {
            return jQuery(
              "<span>" +
              option.text +
              '<span class="ssgsw_disabled-option"> (This field type is not supported yet)</span></span>'
            );
          }
        }
        return option.text;
      },
      sorter: function (data) {
        return data; // Disable default sorting
      }
    });

    select2_alpine.on("select2:select", (evt) => {
      const selectedId = evt.params.data.id;
      if (!this.selectedOrder.includes(selectedId)) {
        this.selectedOrder.push(selectedId);
      }
      this.option.show_custom_fields = this.selectedOrder
      this.save_change = true;
    });

    select2_alpine.on("select2:unselect", (evt) => {
      const unselectedId = evt.params.data.id;
      this.selectedOrder = this.selectedOrder.filter(id => id !== unselectedId);
      this.option.show_custom_fields = this.selectedOrder;
      this.save_change = true;
    });
  },

  /**
   * Get all status options dynamically including custom ones
   */
  getAllStatusOptions() {
    const statusOptions = {};

    // Iterate through all options to find status-related ones
    for (const key in this.option) {
      if (key.startsWith('sync_status_')) {
        statusOptions[key] = this.option[key];
      }
    }

    return statusOptions;
  },
  /**
   * Update Dashboard Settings
   */

  async save_checkbox_settings(key = "") {
    // if (key === "") return;
    try {
      let options = {};
      // console.log("save and sync value " + this.option.save_and_sync);
      if (this.option.save_and_sync) {
        this.option.save_and_sync = false;
      } else {
        this.option.save_and_sync = true;
      }
      if (this.option.multiple_itmes) {
        if (!this.option.multiple_items_enable_first) {
          this.option.multiple_items_enable_first = true;
          this.option.show_product_qt = false;
        }
      }

      const statusOptions = this.getAllStatusOptions();
      // console.log("Status options being saved:", statusOptions);

      options = {

        add_shipping_details_sheet: this.option.add_shipping_details_sheet,
        show_shipping_first_name: this.option.show_shipping_first_name,
        show_shipping_last_name: this.option.show_shipping_last_name,
        show_shipping_address_1: this.option.show_shipping_address_1,
        show_shipping_city: this.option.show_shipping_city,
        show_shipping_postcode: this.option.show_shipping_postcode,
        show_shipping_country: this.option.show_shipping_country,
        show_shipping_address_2: this.option.show_shipping_address_2,
        show_shipping_company: this.option.show_shipping_company,
        show_shipping_state: this.option.show_shipping_state,
        show_shipping_email: this.option.show_shipping_email,
        show_shipping_phone: this.option.show_shipping_phone,


        total_discount: this.option.total_discount,
        sync_order_id: this.option.sync_order_id,
        multiple_itmes: this.option.multiple_itmes,
        order_total: this.option.order_total,
        show_payment_method: this.option.show_payment_method,
        show_total_sales: this.option.show_total_sales,
        show_customer_note: this.option.show_customer_note,
        show_order_url: this.option.show_order_url,
        show_order_date: this.option.show_order_date,
        show_custom_fields: this.option.show_custom_fields,
        show_product_qt: this.option.show_product_qt,
        transaction_id: this.option.transaction_id,
        show_custom_meta_fields: this.option.show_custom_meta_fields,

        separator_type: this.option.separator_type,
        enable_sheet_sorting: this.option.enable_sheet_sorting,
        sorting_criteria: this.option.sorting_criteria,
        sort_order: this.option.sort_order,

        sync_order_products: this.option.sync_order_products,
        sync_order_status: this.option.sync_order_status,


        who_place_order: this.option.who_place_order,
        sync_total_items: this.option.sync_total_items,
        sync_total_price: this.option.sync_total_price,

        make_billing_shipping_seperate: this.option.make_billing_shipping_seperate,

        show_billing_details: this.option.show_billing_details,

        show_billing_first_name: this.option.show_billing_first_name,
        show_billing_last_name: this.option.show_billing_last_name,
        show_billing_address_1: this.option.show_billing_address_1,
        show_billing_city: this.option.show_billing_city,
        show_billing_postcode: this.option.show_billing_postcode,
        show_billing_country: this.option.show_billing_country,
        show_billing_address_2: this.option.show_billing_address_2,
        show_billing_company: this.option.show_billing_company,
        show_billing_state: this.option.show_billing_state,
        show_billing_email: this.option.show_billing_email,
        show_billing_phone: this.option.show_billing_phone,


        custom_order_status_bolean: this.option.custom_order_status_bolean,
        show_order_note: this.option.show_order_note,
        multiple_items_enable_first: this.option.multiple_items_enable_first,
        bulk_edit_option2: this.option.bulk_edit_option2,
        product_sku_sync: this.option.product_sku_sync,
        save_and_sync: this.option.save_and_sync,


        // Unified Google Sheets Filtering Options
        enable_google_sheets_filtering: this.option.enable_google_sheets_filtering,

        // Order Status Filter Options
        enable_order_status_filter: this.option.enable_order_status_filter,

        // All order status sync options (including custom ones)
        ...this.getAllStatusOptions(),

        // Date Filter Options
        enable_date_filter: this.option.enable_date_filter,
        date_filter_type: this.option.date_filter_type || 'days_old',
        date_filter_days: this.option.date_filter_days || 60,
        date_filter_from: this.option.date_filter_from || '',
        date_filter_to: this.option.date_filter_to || '',

      };

      // options[key] = this.option[key];
      let updateResponse = await Ajax.post("osgsw_update_options", {
        options: options,
      });


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

      // Handle update response
      if (!updateResponse.success) {
        Vn.fire({
          icon: "error",
          title: "Oops, settings save failed!",
        });
        return;
      }

      // Sync data to Google Sheet
      const syncResponse = await Ajax.post("osgsw_sync_sheet");


      if (syncResponse.success) {
        const batchSize = 1500;
        const totalItems = syncResponse.message;
        // console.log(totalItems);
        let offset = 0;
        let successCount = 0;
        let errorCount = 0;

        while (offset < totalItems) {
          // Fix: Add isLastBatch flag detection
          const isLastBatch = (offset + batchSize) >= totalItems;
          const batchResponse = await Ajax.post("osgsw_sync_batch_to_sheet", {
            offset,
            batchSize,
            isLastBatch, 
          });
          // console.log(batchResponse);

          if (batchResponse.success) {
            const progress = (((offset + batchSize) / totalItems) * 100).toFixed(2);
            successCount++;
            // Update progress bar
            Vn.fire({
              position: "center",
              timeout: false,
              icon: "info",
              title: "Syncing Products 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;
            }
          }
        }

        if (successCount > 0) {
          // Check if filtering is enabled to show appropriate message
          const isFilteringEnabled = this.option.enable_google_sheets_filtering;
          if (isFilteringEnabled) {
            Vn.fire({
              title: "Order sync successfully!",
              icon: "success",
            });
          } else {
            Vn.fire({
              title: "Great, your settings are saved!",
              icon: "success",
            });
          }
        } else {
          // Check if filtering is enabled and no orders found
          const isFilteringEnabled = this.option.enable_google_sheets_filtering;
          if (isFilteringEnabled) {
            Vn.fire({
              title: "No orders found matching your filtering criteria",
              icon: "info",
            });
          } else {
            Vn.fire({
              title: "Error: Synced on Google Sheet failed!",
              icon: "error",
            });
          }
        }
      } else {
        this.isLoading = false;
        this.save_change = false;

        // Check if filtering is enabled to show appropriate message
        const isFilteringEnabled = this.option.enable_google_sheets_filtering;
        if (isFilteringEnabled) {
          Vn.fire({
            title: "No orders found matching your filtering criteria",
            icon: "info",
          });
        } else {
          Vn.fire({
            title: "Great, your settings are saved!",
            icon: "success",
          });
        }
      }
    } catch (error) {
      console.error("Error while saving settings:", error);
      Vn.fire({
        icon: "error",
        title: "Unexpected error occurred!",
      });
    } finally {
      this.isLoading = false;
      this.save_change = false;
    }

  },

  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("osgsw_update_options", {
      options: {
        setup_step: 2,
      },
    });

    window.location.href =
      osgsw_script.site_url + "/wp-admin/admin.php?page=osgsw-admin";
  },

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

export default () => Dashboard;
