import * as alies_localization from "./wcmlim_localization.js";
import * as alies_getcookies from "./wcmlim_getcookies.js";
import * as alies_setcookies from "./wcmlim_setcookies.js";
import * as alies_selectLocation from "./wcmlim_select_location.js";

var localization = alies_localization.wcmlim_localization();

export function ChangeLc_Select() {

  if (jQuery("#wcmlim-change-lc-select").length > 0) {
    jQuery(".wcmlim-lc-switch").delegate(
      "#wcmlim-change-lc-select",
      "change",
      function (e) {
        if (localization.isClearCart == "on") {
          
          var e_value = jQuery(e.target).val();
          jQuery(this).find("option[jsselect]").removeAttr("jsselect");
          jQuery(this)
            .find('option[value="' + e_value + '"]')
            .attr("jsselect", "jsselect");

          jQuery(".single_add_to_cart_button").prop("disabled", true);
          jQuery(".wcmlim_cart_valid_err").remove();
          jQuery(
            "<div class='wcmlim_cart_valid_err'><center><i class='fas fa-spinner fa-spin'></i></center></div>"
          ).insertAfter(".Wcmlim_loc_label");
          jQuery(document.body).trigger("wc_fragments_refreshed");

          jQuery.ajax({
            type: "POST",
            url: localization.ajaxurl,
            data: {
              e_value : e_value,
              action: "wcmlim_ajax_cart_count",
              security: localization.security,
            },
            success(response) {
              e.preventDefault();
              // NEW: Handle purchase_one_location scenarios
              if (typeof response === 'string' && response.startsWith('{')) {
                try {
                        const responseData = JSON.parse(response);
                        
                        if (responseData.status === 'location_change') {
                            // All products available at new location - offer to change location
                            Swal.fire({
                                title: wc_add_to_cart_params._purchase_change_location_text,
                                text: `Your cart contains items from ${responseData.current_location}. Do you want to change all items to ${responseData.new_location_name}?`,
                                icon: "question",
                                showCancelButton: true,
                                confirmButtonColor: "#3085d6",
                                cancelButtonColor: "#d33",
                                confirmButtonText: "Yes, Change Location!",
                                cancelButtonText: "Cancel"
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    console.log('User confirmed location change');
                                    console.log('Response data:', responseData);
                                    
                                    // Update cart location via AJAX
                                    let ajaxurl;
                                    if (typeof multi_inventory !== 'undefined' && multi_inventory.ajaxurl) {
                                        ajaxurl = multi_inventory.ajaxurl;
                                    } else if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.ajax_url) {
                                        ajaxurl = wc_add_to_cart_params.ajax_url;
                                    } else {
                                        console.error('No AJAX URL found');
                                        Swal.fire({ 
                                            title: "Error!", 
                                            text: "AJAX URL not available. Please refresh the page and try again.", 
                                            icon: "error" 
                                        });
                                        return;
                                    }
                                    
                                    console.log('AJAX URL:', ajaxurl);
                                    
                                    jQuery.ajax({
                                        url: ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_update_cart_location",
                                            new_location_id: responseData.new_location_id,
                                            new_location_key: e_value,
                                            remove_unavailable: false,
                                            security: localization.security
                                        },
                                        beforeSend: function() {
                                            console.log('Sending AJAX request to update cart location');
                                        },
                                        success(updateResponse) {
                                            console.log('AJAX success response:', updateResponse);
                                            try {
                                                const updateData = JSON.parse(updateResponse);
                                                console.log('Parsed response:', updateData);
                                                if (updateData.status === 'success') {
                                                    Swal.fire({ 
                                                        title: "Location Updated!", 
                                                        text: `Cart location changed to ${updateData.new_location}. Product added successfully!`, 
                                                        icon: "success" 
                                                    }).then(() => {
                                                        window.location.href = window.location.href;
                                                    });
                                                } else {
                                                    console.error('Update failed:', updateData);
                                                    Swal.fire({ 
                                                        title: "Error!", 
                                                        text: updateData.message || "Failed to update cart location.", 
                                                        icon: "error" 
                                                    });
                                                }
                                            } catch (e) {
                                                console.error('Error parsing response:', e, updateResponse);
                                                Swal.fire({ 
                                                    title: "Error!", 
                                                    text: "Invalid response from server.", 
                                                    icon: "error" 
                                                });
                                            }
                                        },
                                        error(xhr, status, error) {
                                            console.error('AJAX error:', {xhr, status, error});
                                            console.error('Response text:', xhr.responseText);
                                            Swal.fire({ 
                                                title: "Error!", 
                                                text: "Failed to update cart location: " + error, 
                                                icon: "error" 
                                            });
                                        }
                                    });
                                } else {
                                    console.log('User cancelled location change');
                                    jQuery.ajax({
                                        url: localization.ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_set_location_on_change",
                                            loc_key: responseData.current_location_key,
                                            security: localization.security
                                        },
                                        success: function(response) {
                                            console.log('Cookie reset successful:', response);
                                            // Set cookies on client side as well
                                            alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                            alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                            
                                            jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                            jQuery(".single_add_to_cart_button").prop("disabled", false);
                                            jQuery(".wcmlim_cart_valid_err").remove();
                                            window.location.href = window.location.href;
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Error setting cookies:', error);
                                            // Fallback: set cookies on client side only
                                            alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                            alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                            
                                            jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                            jQuery(".single_add_to_cart_button").prop("disabled", false);
                                            jQuery(".wcmlim_cart_valid_err").remove();
                                            window.location.href = window.location.href;
                                        }
                                    });
                                }
                            });
                            return false;
                        }
                        
                        if (responseData.status === 'unavailable_products') {
                            // Some products not available at new location - offer to clear cart
                            let unavailableList = responseData.unavailable_products.map(p => `• ${p.name} (Qty: ${p.quantity})`).join('\n');
                            
                            Swal.fire({
                                title: wc_add_to_cart_params._purchase_change_location_notavailtext,
                                text: `The following products are not available at ${responseData.new_location_name}:\n\n${unavailableList}\n\nDo you want to remove these products and move the remaining items to ${responseData.new_location_name}?`,
                                icon: "warning",
                                showCancelButton: true,
                                confirmButtonColor: "#d33",
                                cancelButtonColor: "#3085d6",
                                confirmButtonText: "Yes, Remove & Update!",
                                cancelButtonText: "Cancel"
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Remove only unavailable products and update available ones to new location
                                    jQuery.ajax({
                                        url: localization.ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_update_cart_location",
                                            unavailable_products: JSON.stringify(responseData.unavailable_products),
                                            new_location_id: responseData.new_location_id,
                                            new_location_key: e_value,
                                            remove_unavailable: true,
                                            security: localization.security
                                        },
                                        beforeSend: function() {
                                            jQuery(".wcmlim_cart_valid_err").html("<center><i class='fas fa-spinner fa-spin'></i> Updating cart...</center>");
                                        },
                                        success(output) {
                                            console.log('Cart updated successfully:', output);
                                            try {
                                                const updateData = JSON.parse(output);
                                                if (updateData.status === 'success') {
                                                    let message = `Location changed to ${updateData.new_location}.`;
                                                    
                                                    // If products were removed, show details
                                                    if (updateData.removed_products && updateData.removed_products.length > 0) {
                                                        message += `\n\nRemoved products:\n${updateData.removed_products.map(name => `• ${name}`).join('\n')}`;
                                                    }
                                                    
                                                    Swal.fire({ 
                                                        title: "Cart Updated!", 
                                                        text: message,
                                                        icon: "success" 
                                                    }).then(() => {
                                                        // Continue with normal location change processing
                                                        jQuery(".single_add_to_cart_button").prop("disabled", false);
                                                        jQuery(".wcmlim_cart_valid_err").remove();
                                                        alies_selectLocation.select_location("#select_location");
                                                        // Refresh the page to update cart display
                                                        window.location.href = window.location.href;
                                                    });
                                                } else {
                                                    Swal.fire({ 
                                                        title: "Error!", 
                                                        text: updateData.message || "Failed to update cart.", 
                                                        icon: "error" 
                                                    });
                                                }
                                            } catch (e) {
                                                console.error('Error parsing response:', e);
                                                Swal.fire({ 
                                                    title: "Error!", 
                                                    text: "Invalid response from server.", 
                                                    icon: "error" 
                                                });
                                            }
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Error updating cart:', error);
                                            Swal.fire({ 
                                                title: "Error!", 
                                                text: "There was an error updating the cart.", 
                                                icon: "error" 
                                            });
                                            // Reset dropdown to previous location
                                            jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                            jQuery(".single_add_to_cart_button").prop("disabled", false);
                                            jQuery(".wcmlim_cart_valid_err").remove();
                                        }
                                    });
                                } else {
                                    // User cancelled - reset dropdown to previous location
                                    console.log('User cancelled, resetting to previous location');
                                    
                                    // Make AJAX call to set cookies properly on server side
                                    jQuery.ajax({
                                        url: localization.ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_set_location_on_change",
                                            loc_key: responseData.current_location_key,
                                            security: localization.security
                                        },
                                        success: function(response) {
                                            console.log('Cookie reset successful:', response);
                                            // Set cookies on client side as well
                                            alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                            alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                            
                                            jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                            jQuery(".single_add_to_cart_button").prop("disabled", false);
                                            jQuery(".wcmlim_cart_valid_err").remove();
                                            window.location.href = window.location.href;
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Error setting cookies:', error);
                                            // Fallback: set cookies on client side only
                                            alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                            alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                            
                                            jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                            jQuery(".single_add_to_cart_button").prop("disabled", false);
                                            jQuery(".wcmlim_cart_valid_err").remove();
                                            window.location.href = window.location.href;
                                        }
                                    });
                                }
                            });
                            return false;
                        }
                    } catch (e) {
                        // Not a JSON response, continue with normal processing
                    }
              } else {
                window.location.href = window.location.href;
              } 
              
            },
          });
          
        } else {
          jQuery(this).closest("form").submit();
        }
        

        if (localization.isLocationsGroup == "on") {
          const get_regID = jQuery(this)
            .find("option:selected")
            .attr("data-lc-storeid");
          alies_setcookies.setcookie(
            "wcmlim_selected_location_regid",
            get_regID
          );
        } else {
          const get_regID = -1;
          alies_setcookies.setcookie(
            "wcmlim_selected_location_regid",
            get_regID
          );
        }
        const get_termID = jQuery(this)
          .find("option:selected")
          .attr("data-lc-term");
        alies_setcookies.setcookie(
          "wcmlim_selected_location_termid",
          get_termID
        );
      }
    );
  }
}

export function ChangeLcSelectWithLocation() {
  if (
    jQuery("#wcmlim-change-lcselect").length > 0 &&
    localization.isLocationsGroup == "on"
  ) {
    jQuery(".wcmlim-lcswitch").delegate(
      "#wcmlim-change-lcselect",
      "change",
      function (e) {
        jQuery("#select_location").find(":selected").removeAttr("selected");
        const get_loc = jQuery(this).find("option:selected").val();
        jQuery(`#select_location option[value='${get_loc}']`).prop(
          "selected",
          true
        );
        alies_setcookies.setcookie("wcmlim_selected_location", get_loc);
        const get_term2 = jQuery(this)
          .find("option:selected")
          .attr("data-lc-term");
        alies_setcookies.setcookie(
          "wcmlim_selected_location_termid",
          get_term2
        );
        const get_regID = jQuery(this)
          .find("option:selected")
          .attr("data-lc-storeid");
        alies_setcookies.setcookie("wcmlim_selected_location_regid", get_regID);
        alies_selectLocation.select_location("#select_location");
      }
    );
  }
}
