/**
 * Discount Rules Tab
 *
 * Member-only pricing rules — allows active members to receive special
 * discounts on store products based on subscription conditions.
 *
 * Rule structure: IF (conditions) → TARGET (what products) → THEN (discount details)
 *
 * @package ArraySubs
 * @since 1.9.0
 */

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";

/**
 * DiscountRulesTab Component
 *
 * Manages member-only discount rules. Each rule contains:
 * - IF section (conditions — who qualifies)
 * - TARGET section (which products get discounted)
 * - THEN section (discount type, value, application mode)
 */
const DiscountRulesTab = () => {
  const { env } = window.arraySubs;
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [rules, setRules] = useState([]);
  const { toasts, showToast, removeToast } = useToast();

  /**
   * Target scope options — defines what products receive the discount
   */
  const targetScopes = [
    { value: "all", label: __("All products", "arraysubs") },
    {
      value: "specific_products",
      label: __("Specific products", "arraysubs"),
    },
    {
      value: "specific_categories",
      label: __("Specific categories", "arraysubs"),
    },
    { value: "specific_tags", label: __("Specific tags", "arraysubs") },
  ];

  /**
   * Discount type options
   */
  const discountTypes = [
    { value: "percentage", label: __("Percentage (%)", "arraysubs") },
    { value: "fixed", label: __("Fixed amount", "arraysubs") },
  ];

  /**
   * Apply mode options for fixed discounts.
   */
  const applyModes = [
    { value: "per_item", label: __("Per item", "arraysubs") },
    { value: "per_cart", label: __("Per cart", "arraysubs") },
  ];

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

  /**
   * Fetch discount 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?.discount_rules || []);
    } catch (error) {
      showToast(__("Failed to load discount 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({
            discount_rules: rules,
          }),
        },
      );

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

      showToast(
        __("Discount rules saved successfully!", "arraysubs"),
        "success",
      );
    } catch (error) {
      showToast(__("Failed to save discount rules", "arraysubs"), "error");
    } finally {
      setSaving(false);
    }
  };

  /**
   * Get default rule structure for discount rules
   */
  const getDefaultRule = useCallback(() => {
    return {
      enabled: true,
      name: __("New Discount Rule", "arraysubs"),
      conditions: { logic: "and", rules: [] },
      target_scope: "all",
      target_product_ids: [],
      target_category_ids: [],
      target_tag_ids: [],
      exclusion_product_ids: [],
      exclusion_category_ids: [],
      discount_type: "percentage",
      discount_value: 10,
      apply_to: "per_item",
      schedule_enabled: false,
      schedule_value: 0,
      schedule_unit: "days",
    };
  }, []);

  /**
   * Render TARGET section fields — what products get discounted
   */
  const renderTargetFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          {/* Target Scope */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Apply discount to", "arraysubs")}
            </label>
            <select
              value={rule.target_scope || "all"}
              onChange={(e) =>
                updateRule({
                  target_scope: e.target.value,
                  target_product_ids: [],
                  target_category_ids: [],
                  target_tag_ids: [],
                })
              }
              className="arraysubs-rule-field__select"
            >
              {targetScopes.map((scope) => (
                <option key={scope.value} value={scope.value}>
                  {scope.label}
                </option>
              ))}
            </select>
            <p className="arraysubs-rule-field__help">
              {__(
                "Select which products this discount applies to.",
                "arraysubs",
              )}
            </p>
          </div>

          {/* Specific Products (AJAX search) */}
          {rule.target_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 products that will receive this discount.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* Specific Categories (AJAX search) */}
          {rule.target_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 receive the discount.",
                  "arraysubs",
                )}
              </p>
            </div>
          )}

          {/* Specific Tags (AJAX search) */}
          {rule.target_scope === "specific_tags" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Tags", "arraysubs")}
              </label>
              <AjaxSelect
                value={rule.target_tag_ids || []}
                onChange={(ids) => updateRule({ target_tag_ids: ids })}
                endpoint="terms"
                dependsOnValue="product_tag"
                multiple={true}
                placeholder={__("Search tags...", "arraysubs")}
              />
              <p className="arraysubs-rule-field__help">
                {__(
                  "All products with these tags will receive the discount.",
                  "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 never receive this discount, even if they match the target scope above.",
                "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 will be excluded from this discount.",
                "arraysubs",
              )}
            </p>
          </div>
        </>
      );
    },
    [targetScopes],
  );

  /**
   * Render THEN section fields — discount details
   */
  const renderActionFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          <div className="arraysubs-rule-field-row">
            {/* Discount Type */}
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Discount type", "arraysubs")}
              </label>
              <select
                value={rule.discount_type || "percentage"}
                onChange={(e) =>
                  updateRule({
                    discount_type: e.target.value,
                    apply_to:
                      e.target.value === "fixed"
                        ? rule.apply_to || "per_item"
                        : "per_item",
                  })
                }
                className="arraysubs-rule-field__select"
              >
                {discountTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            {/* Discount Value */}
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Discount value", "arraysubs")}
              </label>
              <div className="arraysubs-rule-field__input-group">
                {rule.discount_type === "fixed" && (
                  <span className="arraysubs-rule-field__input-prefix">
                    {window.arraySubs?.env?.currencySymbol || "$"}
                  </span>
                )}
                <input
                  type="number"
                  className="arraysubs-rule-field__input"
                  value={rule.discount_value ?? ""}
                  onChange={(e) => {
                    const val = parseFloat(e.target.value);
                    updateRule({ discount_value: isNaN(val) ? "" : val });
                  }}
                  min="0"
                  max={rule.discount_type === "percentage" ? "100" : undefined}
                  step="0.01"
                  placeholder={
                    rule.discount_type === "percentage" ? "10" : "5.00"
                  }
                />
                {rule.discount_type === "percentage" && (
                  <span className="arraysubs-rule-field__input-suffix">%</span>
                )}
              </div>
              <p className="arraysubs-rule-field__help">
                {rule.discount_type === "percentage"
                  ? __(
                      "Enter a value between 0 and 100. For example, 10 means 10% off the product price.",
                      "arraysubs",
                    )
                  : __(
                      "Enter a fixed amount to subtract from the product price.",
                      "arraysubs",
                    )}
              </p>
            </div>

            {/* Apply Mode */}
            {rule.discount_type === "fixed" && (
              <div className="arraysubs-rule-field">
                <label className="arraysubs-rule-field__label">
                  {__("Apply fixed discount", "arraysubs")}
                </label>
                <select
                  value={rule.apply_to || "per_item"}
                  onChange={(e) => updateRule({ apply_to: e.target.value })}
                  className="arraysubs-rule-field__select"
                >
                  {applyModes.map((mode) => (
                    <option key={mode.value} value={mode.value}>
                      {mode.label}
                    </option>
                  ))}
                </select>
                <p className="arraysubs-rule-field__help">
                  {rule.apply_to === "per_cart"
                    ? __(
                        "Applies once as a cart adjustment across the eligible matched items, capped so it never exceeds their subtotal.",
                        "arraysubs",
                      )
                    : __(
                        "Applies separately to each eligible product line item.",
                        "arraysubs",
                      )}
                </p>
              </div>
            )}
          </div>

          {/* Footnote: how discounts work */}
          <div className="arraysubs-rule-field__footnote">
            <strong>{__("How it works:", "arraysubs")}</strong>
            <ul>
              <li>
                {rule.discount_type === "fixed" && rule.apply_to === "per_cart"
                  ? __(
                      "This rule is applied once per cart as a negative fee. Product prices stay unchanged on catalog pages for this rule type, and the adjustment appears in cart and checkout.",
                      "arraysubs",
                    )
                  : __(
                      "Discounts are applied per-item. Each qualifying product in the cart shows the member price.",
                      "arraysubs",
                    )}
              </li>
              <li>
                {__(
                  "If multiple rules match the same product, the best discount (lowest price) wins — discounts do not stack across rules.",
                  "arraysubs",
                )}
              </li>
              <li>
                {__(
                  "Member discounts are calculated from the regular price by default. If a product is on sale, the better price (sale or member) will be shown.",
                  "arraysubs",
                )}
              </li>
              <li>
                {__(
                  "Per-item discounts are visible on product pages, archives, cart, and checkout for qualifying members. Guests and non-qualifying users see regular prices.",
                  "arraysubs",
                )}
              </li>
            </ul>
          </div>
        </>
      );
    },
    [applyModes, discountTypes],
  );

  /**
   * 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>{__("Discount Rules", "arraysubs")}</h3>
          <p>
            {__(
              "Reward your active members and subscribers with special pricing on store products. Discounts are applied automatically based on the conditions you define below.",
              "arraysubs",
            )}
          </p>
        </div>
      </div>

      <div className="arraysubs-members-access__info-box">
        <h4>{__("How Discount Rules Work", "arraysubs")}</h4>
        <ol>
          <li>
            {__(
              "Define who qualifies using the IF conditions — for example, customers with an active subscription to a specific product or users with a certain role.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Choose what to discount in the TARGET section — all products, specific products, categories, or tags. You can also exclude specific products or categories.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Configure the THEN section — set a percentage or fixed amount off the product price.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "For fixed discounts, you can choose whether the amount applies to each matching item or once per cart. Per-cart discounts appear as a cart adjustment at checkout.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "When a customer qualifies, per-item rules show member pricing across the storefront, while per-cart rules show the adjustment in cart and checkout where the final total is calculated.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Non-qualifying users and guests always see regular prices — no discount information is leaked.",
              "arraysubs",
            )}
          </li>
        </ol>
        <p className="arraysubs-members-access__info-note">
          <strong>{__("Note:", "arraysubs")}</strong>{" "}
          {__(
            "If a customer's membership expires or is cancelled, the discount is immediately removed for future purchases. Existing orders are not affected.",
            "arraysubs",
          )}
        </p>
      </div>

      {/* Rule Builder */}
      <RestrictionRuleBuilder
        rules={rules}
        onChange={setRules}
        ruleType="discount"
        conditionTypes={defaultConditionTypes}
        renderTargetFields={renderTargetFields}
        renderActionFields={renderActionFields}
        getDefaultRule={getDefaultRule}
        ruleLabel={__("Discount 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 DiscountRulesTab;
