import Base from "./Base";
export default class Orders extends Base {
  constructor() {
    super();
    this.waRestoreBtn = document.getElementById("_waRestoreBtn");
    this.waArchiveBtn = document.getElementById("_waArchiveBtn");

    if (this.waRestoreBtn) {
      this.loader();
    }

    // Check if we're on an order edit page and create archive button
    if (this.isOrderEditPage()) { 
      this.initArchiveButton();
    } else if (this.waArchiveBtn) {
      // If button already exists (fallback), attach handler
      this.archiveLoader();
    }

    // Initialize bulk archive confirmation on orders list page
    if (this.isOrdersListPage()) {
      this.initBulkArchiveConfirmation();
    }
  }

  /**
   * Check if current page is order edit page by URL
   * @returns {boolean}
   */
  isOrderEditPage() {
    // Single order archive is always enabled
    const urlParams = new URLSearchParams(window.location.search);
    const pathname = window.location.pathname;

    // Check for HPOS order edit page: admin.php?page=wc-orders&action=edit&id=XXX
    if (pathname.includes("admin.php")) {
      const page = urlParams.get("page");
      const action = urlParams.get("action");
      const id = urlParams.get("id");
      if (page === "wc-orders" && action === "edit" && id) {
        return true;
      }
    }

    // Check for classic order edit page: post.php?post=XXX&action=edit
    if (pathname.includes("post.php")) {
      const action = urlParams.get("action");
      const post = urlParams.get("post");
      if (action === "edit" && post) {
        // Additional check: verify it's a shop_order post type
        // We can check the post type from the URL or page context
        return true;
      }
    }

    return false;
  }

  /**
   * Check if current page is orders list page
   * @returns {boolean}
   */
  isOrdersListPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const pathname = window.location.pathname;

    // Check for HPOS orders list page: admin.php?page=wc-orders
    if (pathname.includes("admin.php")) {
      const page = urlParams.get("page");
      if (page === "wc-orders" && !urlParams.get("action")) {
        return true;
      }
    }

    // Check for classic orders list page: edit.php?post_type=shop_order
    if (pathname.includes("edit.php")) {
      const postType = urlParams.get("post_type");
      if (postType === "shop_order") {
        return true;
      }
    }

    return false;
  }

  /**
   * Get order ID from URL
   * @returns {number|null}
   */
  getOrderIdFromUrl() {
    const urlParams = new URLSearchParams(window.location.search);

    // HPOS: id parameter
    const id = urlParams.get("id");
    if (id) {
      return parseInt(id, 10);
    }

    // Classic: post parameter
    const post = urlParams.get("post");
    if (post) {
      return parseInt(post, 10);
    }

    return null;
  }

  /**
   * Initialize archive button on order edit page
   */
  initArchiveButton() {
    const orderId = this.getOrderIdFromUrl();
    if (!orderId) {
      return;
    }

    // Wait for DOM to be ready and WooCommerce to render
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", () => {
        setTimeout(() => this.createArchiveButton(orderId), 100);
      });
    } else {
      setTimeout(() => this.createArchiveButton(orderId), 100);
    }
  }

  /**
   * Create archive button and append to page
   * @param {number} orderId
   */
  createArchiveButton(orderId) {
    // Check if button already exists
    if (document.getElementById("_waArchiveBtn")) {
      // Button already exists, just attach handler
      this.waArchiveBtn = document.getElementById("_waArchiveBtn");
      this.archiveLoader();
      return;
    }

    // Find the order title heading
    const orderTitle = this.findOrderTitle();
    if (!orderTitle) {
      return;
    }

    // Find target container
    const targetContainer = this.findTargetContainer(orderTitle);
    if (!targetContainer) {
      return;
    }

    // Create button elements
    const buttonWrapper = this.createButtonElements(orderId);

    // Try multiple strategies to place the button
    const buttonPlaced = this.placeButton(
      buttonWrapper,
      targetContainer,
      orderTitle
    );

    if (buttonPlaced) {
      // Attach click handler
      this.waArchiveBtn = document.getElementById("_waArchiveBtn");
      if (this.waArchiveBtn) {
        this.archiveLoader();
      }
    }
  }

  /**
   * Find order title element
   * @returns {HTMLElement|null}
   */
  findOrderTitle() {
    // Try multiple selectors
    const selectors = [
      "h2.wp-heading-inline",
      ".woocommerce-order-data__heading",
      ".woocommerce-order-data h2",
      ".woocommerce-order-data h3",
    ];

    for (const selector of selectors) {
      const elements = document.querySelectorAll(selector);
      for (const el of elements) {
        if (el.textContent && el.textContent.match(/Order\s+#\d+/)) {
          return el;
        }
      }
    }

    // Fallback: find any h2 or h3 containing "Order #"
    const headings = document.querySelectorAll("h2, h3");
    for (const heading of headings) {
      if (heading.textContent && heading.textContent.match(/Order\s+#\d+/)) {
        return heading;
      }
    }

    return null;
  }

  /**
   * Find target container for button placement
   * @param {HTMLElement} orderTitle
   * @returns {HTMLElement|null}
   */
  findTargetContainer(orderTitle) {
    // Try to find header container
    let container = orderTitle.closest(".woocommerce-order-data__header");
    if (container) {
      return container;
    }

    container = orderTitle.closest(".woocommerce-order-data");
    if (container) {
      return container;
    }

    container = orderTitle.closest(".postbox-header");
    if (container) {
      return container;
    }

    // Use parent of title
    if (orderTitle.parentElement) {
      return orderTitle.parentElement;
    }

    // Final fallback: find order data container
    const orderData = document.querySelector(
      ".woocommerce-order-data, #woocommerce-order-data"
    );
    return orderData;
  }

  /**
   * Create button elements
   * @param {number} orderId
   * @returns {HTMLElement}
   */
  createButtonElements(orderId) {
    // Create archive button
    const archiveButton = document.createElement("button");
    archiveButton.type = "button";
    archiveButton.id = "_waArchiveBtn";
    archiveButton.className = "archm-archive-order-btn";
    archiveButton.setAttribute("data-order-id", orderId.toString());

    // Create SVG icon
    const iconSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    iconSvg.setAttribute("width", "11");
    iconSvg.setAttribute("height", "12");
    iconSvg.setAttribute("viewBox", "0 0 11 12");
    iconSvg.setAttribute("fill", "none");
    iconSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    iconSvg.style.width = "12px";
    iconSvg.style.height = "12px";
    iconSvg.style.verticalAlign = "middle";
    
    const iconPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
    iconPath.setAttribute("d", "M0.666667 10.6667C0.489856 10.6667 0.320287 10.7369 0.195262 10.8619C0.070238 10.987 0 11.1565 0 11.3333C0 11.5101 0.070238 11.6797 0.195262 11.8047C0.320287 11.9298 0.489856 12 0.666667 12H10C10.1768 12 10.3464 11.9298 10.4714 11.8047C10.5964 11.6797 10.6667 11.5101 10.6667 11.3333C10.6667 11.1565 10.5964 10.987 10.4714 10.8619C10.3464 10.7369 10.1768 10.6667 10 10.6667H0.666667ZM8.63333 5.53133C8.57142 5.46935 8.49789 5.42018 8.41696 5.38663C8.33603 5.35308 8.24928 5.33581 8.16167 5.33581C8.07406 5.33581 7.98731 5.35308 7.90637 5.38663C7.82544 5.42018 7.75192 5.46935 7.69 5.53133L6 7.222V0.666667C6 0.489856 5.92976 0.320286 5.80474 0.195262C5.67971 0.0702379 5.51014 0 5.33333 0C5.15652 0 4.98695 0.0702379 4.86193 0.195262C4.7369 0.320286 4.66667 0.489856 4.66667 0.666667V7.222L2.976 5.53133C2.85091 5.40633 2.68128 5.33614 2.50443 5.3362C2.32758 5.33626 2.15801 5.40657 2.033 5.53167C1.90799 5.65676 1.8378 5.82639 1.83786 6.00324C1.83793 6.18008 1.90824 6.34966 2.03333 6.47467L4.862 9.30267C4.98702 9.42765 5.15656 9.49786 5.33333 9.49786C5.51011 9.49786 5.67965 9.42765 5.80467 9.30267L8.63333 6.47467C8.69532 6.41275 8.74449 6.33923 8.77804 6.25829C8.81159 6.17736 8.82886 6.09061 8.82886 6.003C8.82886 5.91539 8.81159 5.82864 8.77804 5.74771C8.74449 5.66677 8.69532 5.59325 8.63333 5.53133Z");
    iconPath.setAttribute("fill", "currentColor");
    iconSvg.appendChild(iconPath);
    archiveButton.appendChild(iconSvg);

    // Add text node
    archiveButton.appendChild(document.createTextNode(" Archive Order"));

    // Create help icon
    const helpIcon = document.createElement("span");
    helpIcon.className = "archm-help-icon";
    helpIcon.setAttribute(
      "data-tooltip",
      "This order will be moved to archived storage and will no longer be accessible in the Orders list. To view it again, you'll need to restore it from the archived orders."
    );

    const helpIconDashicon = document.createElement("span");
    helpIconDashicon.className = "dashicons dashicons-editor-help";
    helpIcon.appendChild(helpIconDashicon);

    // Wrap button and help icon
    const buttonWrapper = document.createElement("div");
    buttonWrapper.className = "archm-archive-button-container";
    buttonWrapper.appendChild(archiveButton);
    buttonWrapper.appendChild(helpIcon);

    return buttonWrapper;
  }

  /**
   * Place button using multiple strategies
   * @param {HTMLElement} buttonWrapper
   * @param {HTMLElement} targetContainer
   * @param {HTMLElement} orderTitle
   * @returns {boolean}
   */
  placeButton(buttonWrapper, targetContainer, orderTitle) {
    // Strategy 1: Find header row
    const headerRow = targetContainer.querySelector(
      ".woocommerce-order-data__header"
    );
    if (headerRow) {
      this.setFlexStyles(headerRow);
      headerRow.appendChild(buttonWrapper);
      return true;
    }

    // Strategy 2: Find payment info area
    const paymentInfo = this.findPaymentInfo(targetContainer);
    if (paymentInfo && paymentInfo.parentElement) {
      const paymentParent = paymentInfo.parentElement;
      if (!paymentParent.classList.contains("archm-order-header-wrapper")) {
        this.setFlexStyles(paymentParent);
        paymentParent.style.width = "100%";
        paymentParent.style.marginBottom = "15px";
        paymentParent.appendChild(buttonWrapper);
        return true;
      }
    }

    // Strategy 3: Wrap order title in flex container
    if (
      orderTitle &&
      !orderTitle.parentElement.classList.contains("archm-order-header-wrapper")
    ) {
      const wrapper = document.createElement("div");
      wrapper.className = "archm-order-header-wrapper";
      this.setFlexStyles(wrapper);
      wrapper.style.width = "100%";
      wrapper.style.marginBottom = "15px";

      orderTitle.parentElement.insertBefore(wrapper, orderTitle);
      wrapper.appendChild(orderTitle);
      wrapper.appendChild(buttonWrapper);
      return true;
    }

    // Strategy 4: Fallback - absolute positioning
    targetContainer.style.position = "relative";
    targetContainer.style.paddingTop = "40px";
    buttonWrapper.style.position = "absolute";
    buttonWrapper.style.top = "0";
    buttonWrapper.style.right = "0";
    buttonWrapper.style.zIndex = "10";
    targetContainer.insertBefore(buttonWrapper, targetContainer.firstChild);
    return true;
  }

  /**
   * Set flexbox styles on element
   * @param {HTMLElement} element
   */
  setFlexStyles(element) {
    element.style.display = "flex";
    element.style.justifyContent = "space-between";
    element.style.alignItems = "center";
  }

  /**
   * Find payment info element
   * @param {HTMLElement} container
   * @returns {HTMLElement|null}
   */
  findPaymentInfo(container) {
    const paragraphs = container.querySelectorAll(".woocommerce-order-data p");
    for (const p of paragraphs) {
      const text = p.textContent || "";
      if (text.includes("Payment") || text.includes("Customer IP")) {
        return p;
      }
    }
    return null;
  }

  loader() {
    this.waRestoreBtn.onclick = async (event) => {
      this.loaderMessage = this.JSAlert.loader(
        "Restoring order. Please wait..."
      );
      await this.restoreOrderHandler(event);
    };
  }

  archiveLoader() {
    this.waArchiveBtn.onclick = async (event) => {
      const confirmed = await this.showArchiveConfirmModal();
      if (confirmed) {
        this.loaderMessage = this.JSAlert.loader(
          "Archiving order. Please wait..."
        );
        await this.archiveOrderHandler(event);
      }
    };
  }

  /**
   * Show custom archive confirmation modal
   * @param {Object} options - Modal options
   * @param {boolean} options.isBulk - Whether this is a bulk action
   * @param {number} options.orderCount - Number of orders (for bulk actions)
   * @returns {Promise<boolean>}
   */
  showArchiveConfirmModal(options = {}) {
    const { isBulk = false, orderCount = 0 } = options;

    return new Promise((resolve) => {
      // Remove existing modal if any
      const existingModal = document.getElementById("archm-archive-confirm-modal");
      if (existingModal) {
        existingModal.remove();
      }

      // Create modal overlay
      const overlay = document.createElement("div");
      overlay.className = "archm-modal-overlay";
      overlay.id = "archm-archive-confirm-modal-overlay";

      // Create modal container
      const modal = document.createElement("div");
      modal.className = "archm-archive-confirm-modal";
      modal.id = "archm-archive-confirm-modal";

      // Create modal header
      const header = document.createElement("div");
      header.className = "archm-modal-header";

      const title = document.createElement("h2");
      title.className = "archm-modal-title";
      title.textContent = isBulk 
        ? `Archive ${orderCount} ${orderCount === 1 ? 'order' : 'orders'}?`
        : "Archive this order?";

      const closeBtn = document.createElement("button");
      closeBtn.className = "archm-modal-close";
      closeBtn.type = "button";
      closeBtn.setAttribute("aria-label", "Close");
      closeBtn.innerHTML = "×";

      header.appendChild(title);
      header.appendChild(closeBtn);

      // Create modal body
      const body = document.createElement("div");
      body.className = "archm-modal-body";
      body.textContent = isBulk
        ? `The selected ${orderCount === 1 ? 'order' : 'orders'} will be moved to archived storage and will no longer be accessible in the Orders list. To view ${orderCount === 1 ? 'it' : 'them'} again, you'll need to restore ${orderCount === 1 ? 'it' : 'them'} from the archive. Continue?`
        : "This order will be moved to archived storage and will no longer be accessible in the Orders list. To view it again, you'll need to restore it from the archive. Continue?";

      // Create modal footer with buttons
      const footer = document.createElement("div");
      footer.className = "archm-modal-footer";

      const archiveBtn = document.createElement("button");
      archiveBtn.className = "archm-modal-btn archm-modal-btn-primary";
      archiveBtn.type = "button";
      archiveBtn.textContent = isBulk ? "Archive Orders" : "Archive Order";

      const cancelBtn = document.createElement("button");
      cancelBtn.className = "archm-modal-btn archm-modal-btn-secondary";
      cancelBtn.type = "button";
      cancelBtn.textContent = "Cancel";

      footer.appendChild(archiveBtn);
      footer.appendChild(cancelBtn);

      // Assemble modal
      modal.appendChild(header);
      modal.appendChild(body);
      modal.appendChild(footer);
      overlay.appendChild(modal);
      document.body.appendChild(overlay);

      // Handle close events
      const closeModal = (result) => {
        overlay.remove();
        resolve(result);
      };

      // Close button click
      closeBtn.onclick = () => closeModal(false);

      // Cancel button click
      cancelBtn.onclick = () => closeModal(false);

      // Archive button click
      archiveBtn.onclick = () => closeModal(true);

      // Overlay click (outside modal)
      overlay.onclick = (e) => {
        if (e.target === overlay) {
          closeModal(false);
        }
      };

      // ESC key press
      const handleEsc = (e) => {
        if (e.key === "Escape") {
          closeModal(false);
          document.removeEventListener("keydown", handleEsc);
        }
      };
      document.addEventListener("keydown", handleEsc);

      // Focus on primary button for accessibility
      archiveBtn.focus();
    });
  }

  async restoreOrderHandler(event) {
    try {
      const handler = event.target;
      const post_id = handler.getAttribute("data-post-id");
      const data = new FormData();

      data.append("action", "archm_restore_post");
      data.append("nonce", this.nonce);
      data.append("post_id", post_id);

      const response = await fetch(this.ajaxUrl, {
        method: "POST",
        body: data,
      });

      if (!response.ok) return false;
      const result = await response.json();

      if (result.success) {
        this.loaderMessage.dismissIn(0);
        this.alertSuccess({
          title: "Order restored successfully!",
        });
        setTimeout(() => {
          location.reload();
        }, 200);
      } else {
        this.alertError({
          title: "Order restore error. please try again later!",
        });
      }
    } catch (e) {
      console.error(e);
    }
  }

  async archiveOrderHandler(event) {
    try {
      const handler = event.target;
      const order_id = handler.getAttribute("data-order-id");

      if (!order_id) {
        this.loaderMessage.dismissIn(0);
        this.alertError({
          title: "Order ID not found. Please refresh the page and try again.",
        });
        return false;
      }

      // Use REST API endpoint for archiving
      const response = await fetch(
        archm_admin.rest_url + "archm/v1/archive-single-order",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": archm_admin.rest_nonce,
          },
          body: JSON.stringify({
            order_id: parseInt(order_id),
          }),
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();

      if (result.success) {
        this.loaderMessage.dismissIn(0);
        this.alertSuccess({
          title: "Order archived successfully!",
        });
        // Redirect to orders page after successful archiving
        // Add cache-busting parameter to ensure fresh page load with updated filter
        setTimeout(() => {
          const ordersUrl = archm_admin.orders_url || 
            archm_admin.admin_url + "edit.php?post_type=shop_order";
          const separator = ordersUrl.includes('?') ? '&' : '?';
          window.location.href = ordersUrl + separator + '_archm_refresh=' + Date.now();
        }, 1500);
      } else {
        this.loaderMessage.dismissIn(0);
        this.alertError({
          title:
            result.message ||
            "Failed to archive order. Please try again later!",
        });
      }
    } catch (e) {
      console.error("Archive order error:", e);
      this.loaderMessage.dismissIn(0);
      this.alertError({
        title:
          "Network error occurred. Please check your connection and try again.",
      });
    }
  }

  /**
   * Initialize bulk archive confirmation handler
   */
  initBulkArchiveConfirmation() {
    // Wait for DOM to be ready
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", () => {
        this.setupBulkArchiveHandler();
      });
    } else {
      this.setupBulkArchiveHandler();
    }
  }

  /**
   * Setup bulk archive form submission handler
   */
  setupBulkArchiveHandler() {
    // Find the bulk action form
    // For classic orders: #posts-filter
    // For HPOS: #mainform or form containing bulk actions
    const forms = document.querySelectorAll('form#posts-filter, form#mainform, form[method="get"]');
    
    forms.forEach((form) => {
      // Check if this form has bulk action dropdown
      const bulkActionSelect = form.querySelector('select[name="action"], select[name="action2"]');
      if (!bulkActionSelect) {
        return;
      }

      // Check if Archive Order action exists in the dropdown
      const archiveOption = Array.from(bulkActionSelect.options).find(
        (option) => option.value === 'archm_archive_order'
      );
      
      if (!archiveOption) {
        return;
      }

      // Find the Apply button (could be #doaction or #doaction2)
      const applyButtons = form.querySelectorAll('#doaction, #doaction2, button[type="submit"]');
      
      if (applyButtons.length === 0) {
        return;
      }

      // Create submit handler function
      const submitHandler = async (e) => {
        // Get the selected bulk action
        const actionSelect = form.querySelector('select[name="action"]');
        const action2Select = form.querySelector('select[name="action2"]');
        
        // Determine which action is selected (action takes precedence over action2)
        let selectedAction = '';
        if (actionSelect && actionSelect.value && actionSelect.value !== '-1') {
          selectedAction = actionSelect.value;
        } else if (action2Select && action2Select.value && action2Select.value !== '-1') {
          selectedAction = action2Select.value;
        }

        // Check if Archive Order is selected
        if (selectedAction === 'archm_archive_order') {
          // Count selected orders
          const checkboxes = form.querySelectorAll('input[name="post[]"]:checked, input[name="id[]"]:checked');
          const orderCount = checkboxes.length;

          if (orderCount === 0) {
            // No orders selected, let default validation handle it
            return;
          }

          // Prevent default form submission
          e.preventDefault();
          e.stopPropagation();

          // Show confirmation modal
          const confirmed = await this.showArchiveConfirmModal({
            isBulk: true,
            orderCount: orderCount
          });

          if (confirmed) {
            // User confirmed, proceed with form submission
            // Remove the event listener temporarily to avoid infinite loop
            form.removeEventListener('submit', submitHandler);
            form.submit();
          }
          // If cancelled, do nothing - form submission is already prevented
        }
      };

      // Intercept form submission
      form.addEventListener('submit', submitHandler);
    });
  }
}
