/**
 * Shop Access Rules Tab
 *
 * Members-only shop access restrictions — controls product visibility
 * and purchasing access based on membership conditions.
 *
 * Rule structure: IF (conditions) → TARGET (what products) → THEN (action when denied)
 *
 * @package ArraySubs
 */

import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { buildUrl } from "@libs/url";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import { Skeleton } from "@libs/skeleton";
import RestrictionRuleBuilder, {
  defaultConditionTypes,
} from "@/components/RestrictionRuleBuilder";
import AjaxSelect from "@/components/RestrictionRuleBuilder/AjaxSelect";

/**
 * EcommerceRulesTab Component
 *
 * Manages members-only shop access rules. Each rule contains:
 * - IF section (conditions — who qualifies for access)
 * - TARGET section (restriction scope — what products are restricted)
 * - THEN section (access behavior — what happens when denied)
 */
const EcommerceRulesTab = () => {
  const { env } = window.arraySubs;
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [rules, setRules] = useState([]);
  const { toasts, showToast, removeToast } = useToast();

  /**
   * Restriction scope options — what products are restricted
   */
  const scopeTypes = [
    { value: "all", label: __("Full store (all products)", "arraysubs") },
    {
      value: "specific_products",
      label: __("Specific products", "arraysubs"),
    },
    {
      value: "specific_categories",
      label: __("Specific categories", "arraysubs"),
    },
  ];

  /**
   * Action types — what happens when a non-qualifying user hits a restricted product
   */
  const actionTypes = [
    {
      value: "block_purchase",
      label: __("Show product, block purchase", "arraysubs"),
    },
    { value: "404", label: __("Return 404 (product not found)", "arraysubs") },
    {
      value: "redirect_login",
      label: __("Redirect to login page", "arraysubs"),
    },
    {
      value: "redirect_page",
      label: __("Redirect to a specific page", "arraysubs"),
    },
  ];

  /**
   * Load settings on mount
   */
  useEffect(() => {
    loadData();
  }, []);

  /**
   * Fetch shop access rules from server
   */
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        buildUrl(`${env?.apiBaseUrl}arraysubs/v1/members-access/settings`, {}),
        { headers: { "X-WP-Nonce": env?.nonce } },
      );

      if (!response.ok) {
        throw new Error(__("Failed to load settings", "arraysubs"));
      }

      const data = await response.json();
      setRules(data.data?.ecommerce_rules || []);
    } catch (error) {
      showToast(__("Failed to load shop access rules", "arraysubs"), "error");
    } finally {
      setLoading(false);
    }
  };

  /**
   * Save rules to server
   */
  const saveRules = async () => {
    setSaving(true);
    try {
      const response = await fetch(
        buildUrl(`${env?.apiBaseUrl}arraysubs/v1/members-access/settings`, {}),
        {
          method: "POST",
          headers: {
            "X-WP-Nonce": env?.nonce,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ecommerce_rules: rules,
          }),
        },
      );

      if (!response.ok) {
        throw new Error(__("Failed to save rules", "arraysubs"));
      }

      showToast(
        __("Shop Access rules saved successfully!", "arraysubs"),
        "success",
      );
    } catch (error) {
      showToast(__("Failed to save shop access rules", "arraysubs"), "error");
    } finally {
      setSaving(false);
    }
  };

  /**
   * Get default rule structure for shop access rules
   */
  const getDefaultRule = useCallback(() => {
    return {
      enabled: true,
      name: __("New Shop Access Rule", "arraysubs"),
      conditions: { logic: "and", rules: [] },
      scope: "all",
      target_product_ids: [],
      target_category_ids: [],
      exclusion_product_ids: [],
      exclusion_category_ids: [],
      action: "block_purchase",
      redirect_url: "",
      message: __(
        "This product is available to members only. Join now to unlock purchasing.",
        "arraysubs",
      ),
      schedule_enabled: false,
      schedule_value: 0,
      schedule_unit: "days",
    };
  }, []);

  /**
   * Render TARGET section fields — restriction scope and exclusions
   */
  const renderTargetFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          {/* Restriction Scope */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Restrict access to", "arraysubs")}
            </label>
            <select
              value={rule.scope || "all"}
              onChange={(e) =>
                updateRule({
                  scope: e.target.value,
                  target_product_ids: [],
                  target_category_ids: [],
                })
              }
              className="arraysubs-rule-field__select"
            >
              {scopeTypes.map((scope) => (
                <option key={scope.value} value={scope.value}>
                  {scope.label}
                </option>
              ))}
            </select>
            <p className="arraysubs-rule-field__help">
              {__(
                "Select which products are restricted for non-qualifying users.",
                "arraysubs",
              )}
            </p>
          </div>

          {/* Specific Products (AJAX search) */}
          {rule.scope === "specific_products" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Products", "arraysubs")}
              </label>
              <AjaxSelect
                value={rule.target_product_ids || []}
                onChange={(ids) => updateRule({ target_product_ids: ids })}
                endpoint="products"
                multiple={true}
                placeholder={__("Search products...", "arraysubs")}
              />
              <p className="arraysubs-rule-field__help">
                {__(
                  "Search and select the products to restrict. Variable products restrict all variations.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* Specific Categories (AJAX search) */}
          {rule.scope === "specific_categories" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Categories", "arraysubs")}
              </label>
              <AjaxSelect
                value={rule.target_category_ids || []}
                onChange={(ids) => updateRule({ target_category_ids: ids })}
                endpoint="terms"
                dependsOnValue="product_cat"
                multiple={true}
                placeholder={__("Search categories...", "arraysubs")}
              />
              <p className="arraysubs-rule-field__help">
                {__(
                  "All products in these categories will be restricted.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* ── Exclusions ── */}
          <div className="arraysubs-rule-field__divider">
            <span>{__("Exclusions", "arraysubs")}</span>
          </div>

          {/* Exclude Products */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Exclude products", "arraysubs")}
            </label>
            <AjaxSelect
              value={rule.exclusion_product_ids || []}
              onChange={(ids) => updateRule({ exclusion_product_ids: ids })}
              endpoint="products"
              multiple={true}
              placeholder={__("Search products to exclude...", "arraysubs")}
            />
            <p className="arraysubs-rule-field__help">
              {__(
                "These products will remain accessible even if they match the restriction scope above. Use this to exempt free samples, landing page products, or sign-up products.",
                "arraysubs",
              )}
            </p>
          </div>

          {/* Exclude Categories */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Exclude categories", "arraysubs")}
            </label>
            <AjaxSelect
              value={rule.exclusion_category_ids || []}
              onChange={(ids) => updateRule({ exclusion_category_ids: ids })}
              endpoint="terms"
              dependsOnValue="product_cat"
              multiple={true}
              placeholder={__("Search categories to exclude...", "arraysubs")}
            />
            <p className="arraysubs-rule-field__help">
              {__(
                "Products in these categories remain accessible regardless of the restriction scope.",
                "arraysubs",
              )}
            </p>
          </div>
        </>
      );
    },
    [scopeTypes],
  );

  /**
   * Render THEN section fields — action when access is denied
   */
  const renderActionFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          {/* Action */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__(
                "When a non-qualifying user visits a restricted product",
                "arraysubs",
              )}
            </label>
            <select
              value={rule.action || "block_purchase"}
              onChange={(e) => updateRule({ action: e.target.value })}
              className="arraysubs-rule-field__select"
            >
              {actionTypes.map((action) => (
                <option key={action.value} value={action.value}>
                  {action.label}
                </option>
              ))}
            </select>
            <p className="arraysubs-rule-field__help">
              {rule.action === "block_purchase" &&
                __(
                  "The product page is visible but the Add to Cart button is hidden. A custom message is shown instead.",
                  "arraysubs",
                )}
              {rule.action === "404" &&
                __(
                  "The product returns a 404 as if it does not exist. It is also hidden from shop archives, search, sitemaps, related products, and widgets.",
                  "arraysubs",
                )}
              {rule.action === "redirect_login" &&
                __(
                  "Non-qualifying users are redirected to the WordPress login page.",
                  "arraysubs",
                )}
              {rule.action === "redirect_page" &&
                __(
                  "Non-qualifying users are redirected to a page you specify (e.g. a membership sign-up page).",
                  "arraysubs",
                )}
            </p>
          </div>

          {/* Redirect URL (conditional — only for redirect_page) */}
          {rule.action === "redirect_page" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Redirect URL", "arraysubs")}
              </label>
              <input
                type="text"
                className="arraysubs-rule-field__input"
                value={rule.redirect_url || ""}
                onChange={(e) => updateRule({ redirect_url: e.target.value })}
                placeholder={__("/membership/", "arraysubs")}
              />
              <p className="arraysubs-rule-field__help">
                {__(
                  "Enter the URL to redirect non-qualifying users to. Use a relative path (e.g. /pricing/) or a full URL.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* Custom Message (conditional — only for block_purchase) */}
          {rule.action === "block_purchase" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Custom message", "arraysubs")}
              </label>
              <textarea
                className="arraysubs-rule-field__textarea"
                value={rule.message || ""}
                onChange={(e) => updateRule({ message: e.target.value })}
                placeholder={__(
                  "This product is available to members only. Join now to unlock purchasing.",
                  "arraysubs",
                )}
                rows={3}
              />
              <p className="arraysubs-rule-field__help">
                {__(
                  "This message replaces the Add to Cart button on the product page for non-qualifying users. Basic HTML is allowed.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* Footnote: how this action works */}
          <div className="arraysubs-rule-field__footnote">
            <strong>{__("How it works:", "arraysubs")}</strong>
            <ul>
              {rule.action === "404" && (
                <>
                  <li>
                    {__(
                      "Restricted products are completely hidden from the store — shop pages, search results, category archives, related products, upsells/cross-sells, and product widgets will not show them.",
                      "arraysubs",
                    )}
                  </li>
                  <li>
                    {__(
                      "Visiting a hidden product URL directly returns a 404 Not Found page.",
                      "arraysubs",
                    )}
                  </li>
                  <li>
                    {__(
                      "Hidden products are automatically excluded from XML sitemaps to prevent SEO issues.",
                      "arraysubs",
                    )}
                  </li>
                </>
              )}
              {rule.action === "block_purchase" && (
                <>
                  <li>
                    {__(
                      "Product pages remain visible and indexable by search engines, but the Add to Cart button and purchase form are removed for non-qualifying users.",
                      "arraysubs",
                    )}
                  </li>
                  <li>
                    {__(
                      "Your custom message is displayed in place of the purchase button, encouraging users to join.",
                      "arraysubs",
                    )}
                  </li>
                  <li>
                    {__(
                      "Direct add-to-cart links (?add-to-cart=ID) and REST API / Store API requests are also blocked.",
                      "arraysubs",
                    )}
                  </li>
                </>
              )}
              {(rule.action === "redirect_login" ||
                rule.action === "redirect_page") && (
                <>
                  <li>
                    {__(
                      "Non-qualifying users are immediately redirected when they try to view a restricted product page.",
                      "arraysubs",
                    )}
                  </li>
                  <li>
                    {__(
                      "Products remain visible in shop archives but clicking through triggers the redirect.",
                      "arraysubs",
                    )}
                  </li>
                </>
              )}
              <li>
                {__(
                  "Administrators and shop managers always bypass shop access restrictions so they can manage the store normally.",
                  "arraysubs",
                )}
              </li>
              <li>
                {__(
                  "If multiple rules match the same product, the first matching rule wins (rules are processed in order).",
                  "arraysubs",
                )}
              </li>
              <li>
                {__(
                  "Cart and checkout validation ensures restricted items cannot be purchased even if added before restrictions applied.",
                  "arraysubs",
                )}
              </li>
            </ul>
          </div>
        </>
      );
    },
    [actionTypes],
  );

  /**
   * Render loading state
   */
  if (loading) {
    return (
      <div className="arraysubs-members-access__tab-content">
        <Skeleton count={3} height={100} />
      </div>
    );
  }

  return (
    <div className="arraysubs-members-access__tab-content">
      {/* Header with description */}
      <div className="arraysubs-members-access__section-header">
        <div className="arraysubs-members-access__section-info">
          <h3>{__("Shop Access Rules", "arraysubs")}</h3>
          <p>
            {__(
              "Control which products are accessible or purchasable based on membership conditions. Turn your store into a members-only shopping experience.",
              "arraysubs",
            )}
          </p>
        </div>
      </div>

      <div className="arraysubs-members-access__info-box">
        <h4>{__("How Shop Access Rules Work", "arraysubs")}</h4>
        <ol>
          <li>
            {__(
              "Define who qualifies using the IF conditions — for example, customers with an active subscription, users with a certain role, or customers who purchased a specific product.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Choose what to restrict in the TARGET section — the full store, specific products, or specific categories. Use exclusions to exempt certain products such as free samples or sign-up products.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Configure the THEN section — show a 404, redirect users, or show the product page with purchasing blocked and a custom message displayed.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Non-qualifying users are blocked at every entry point: product pages, direct URLs, add-to-cart links, the cart, checkout, and the WooCommerce Store API (for block-based storefronts).",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "When a customer gains a qualifying membership (e.g. subscribes to the required plan), restrictions are immediately lifted.",
              "arraysubs",
            )}
          </li>
        </ol>
        <p className="arraysubs-members-access__info-note">
          <strong>{__("Note:", "arraysubs")}</strong>{" "}
          {__(
            "Administrators and shop managers always bypass shop access restrictions. Products hidden via the 404 action are automatically excluded from XML sitemaps and product recommendation widgets.",
            "arraysubs",
          )}
        </p>
      </div>

      {/* Rule Builder */}
      <RestrictionRuleBuilder
        rules={rules}
        onChange={setRules}
        ruleType="ecommerce"
        conditionTypes={defaultConditionTypes}
        renderTargetFields={renderTargetFields}
        renderActionFields={renderActionFields}
        getDefaultRule={getDefaultRule}
        ruleLabel={__("Shop Access Rule", "arraysubs")}
        showSchedule
      />

      {/* Save Button */}
      {rules.length > 0 && (
        <div className="arraysubs-members-access__actions arraysubs-bottom-fixed-actions">
          <div>
            <button
              type="button"
              className="button button-primary"
              onClick={saveRules}
              disabled={saving}
            >
              {saving
                ? __("Saving...", "arraysubs")
                : __("Save Rules", "arraysubs")}
            </button>
          </div>
        </div>
      )}

      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </div>
  );
};

export default EcommerceRulesTab;
