/**
 * RestrictionRuleBuilder - Main Component
 *
 * A reusable rule builder component for restriction rules with conditions and actions
 *
 * @package ArraySubs
 */

import React, { useState } from "react";
import { __ } from "@wordpress/i18n";
import {
  Plus,
  List,
  ChevronUp,
  ChevronDown,
  ChevronRight,
  Trash2,
  Copy,
} from "lucide-react";
import ConditionBuilder from "./ConditionBuilder";
import ScheduleFields from "./ScheduleFields";
import { useConfirm } from "@libs/confirm-dialog";
import "./styles.scss";

/**
 * Default condition types available for all tabs
 */
export const defaultConditionTypes = [
  {
    value: "lifetime_spent",
    label: __("Lifetime Purchase Amount", "arraysubs"),
    fields: [
      {
        name: "operator",
        type: "select",
        label: __("Operator", "arraysubs"),
        options: [
          { value: ">=", label: ">=" },
          { value: ">", label: ">" },
          { value: "=", label: "=" },
          { value: "<", label: "<" },
          { value: "<=", label: "<=" },
        ],
        defaultValue: ">=",
      },
      {
        name: "amount",
        type: "number",
        label: __("Amount", "arraysubs"),
        prefix: "$",
        defaultValue: 100,
      },
    ],
  },
  {
    value: "purchased_product",
    label: __("Purchased Product", "arraysubs"),
    fields: [
      {
        name: "product_ids",
        type: "ajax_select",
        label: __("Products", "arraysubs"),
        endpoint: "products",
        multiple: true,
        placeholder: __("Search products...", "arraysubs"),
      },
    ],
  },
  {
    value: "purchased_variation",
    label: __("Purchased Variation", "arraysubs"),
    fields: [
      {
        name: "variation_ids",
        type: "ajax_select",
        label: __("Variations", "arraysubs"),
        endpoint: "variations",
        multiple: true,
        placeholder: __("Search variations...", "arraysubs"),
      },
    ],
  },
  {
    value: "purchased_from_group",
    label: __("Purchased from Category/Tag", "arraysubs"),
    fields: [
      {
        name: "taxonomy",
        type: "ajax_select",
        label: __("Taxonomy", "arraysubs"),
        endpoint: "taxonomies",
        placeholder: __("Select taxonomy...", "arraysubs"),
      },
      {
        name: "term_ids",
        type: "ajax_select",
        label: __("Terms", "arraysubs"),
        endpoint: "terms",
        dependsOn: "taxonomy",
        multiple: true,
        placeholder: __("Select terms...", "arraysubs"),
      },
    ],
  },
  {
    value: "has_active_subscription",
    label: __("Has Active Subscription", "arraysubs"),
    fields: [
      {
        name: "product_ids",
        type: "ajax_select",
        label: __("Products", "arraysubs"),
        endpoint: "products?type=subscription",
        multiple: true,
        placeholder: __("Any subscription (leave empty)", "arraysubs"),
      },
    ],
  },
  {
    value: "has_subscription_variation",
    label: __("Has Subscription Variation", "arraysubs"),
    fields: [
      {
        name: "variation_ids",
        type: "ajax_select",
        label: __("Variations", "arraysubs"),
        endpoint: "variations?type=subscription",
        multiple: true,
        placeholder: __("Search variations...", "arraysubs"),
      },
    ],
  },
  {
    value: "feature_value",
    label: __("Feature Value (Feature Manager)", "arraysubs"),
    fields: [
      {
        name: "feature_key",
        type: "ajax_select",
        label: __("Feature", "arraysubs"),
        endpoint: "features",
        placeholder: __("Select feature...", "arraysubs"),
      },
      {
        name: "operator",
        type: "select",
        label: __("Operator", "arraysubs"),
        options: [
          { value: ">=", label: ">=" },
          { value: ">", label: ">" },
          { value: "=", label: "=" },
          { value: "<", label: "<" },
          { value: "<=", label: "<=" },
        ],
        defaultValue: ">=",
      },
      {
        name: "value",
        type: "number",
        label: __("Value", "arraysubs"),
        defaultValue: 1,
      },
      {
        name: "aggregation",
        type: "select",
        label: __("Aggregation", "arraysubs"),
        options: [
          { value: "sum", label: __("Sum", "arraysubs") },
          { value: "max", label: __("Max", "arraysubs") },
          { value: "any", label: __("Any", "arraysubs") },
        ],
        defaultValue: "sum",
      },
    ],
  },
  {
    value: "user_role",
    label: __("User Role", "arraysubs"),
    fields: [
      {
        name: "roles",
        type: "ajax_select",
        label: __("Roles", "arraysubs"),
        endpoint: "roles",
        multiple: true,
        placeholder: __("Select roles...", "arraysubs"),
      },
    ],
  },
];

/**
 * RestrictionRuleBuilder Component
 *
 * @param {Object} props Component props
 * @param {Array} props.rules Current rules array
 * @param {Function} props.onChange Callback when rules change
 * @param {string} props.ruleType Type of rule (role_mapping, url, cpt, downloads)
 * @param {Array} props.conditionTypes Available condition types
 * @param {Function} props.renderActionFields Render function for action fields
 * @param {Function} props.renderTargetFields Render function for target fields (optional)
 * @param {Function} props.getDefaultRule Function that returns default rule object
 * @param {string} props.ruleLabel Label for rules (e.g., "Role Mapping Rule")
 * @param {boolean} props.showSchedule Whether to show schedule/dripping fields (default: false)
 */
const RestrictionRuleBuilder = ({
  rules = [],
  onChange,
  ruleType = "role_mapping",
  conditionTypes = defaultConditionTypes,
  renderActionFields,
  renderTargetFields,
  getDefaultRule,
  ruleLabel = __("Rule", "arraysubs"),
  showSchedule = false,
}) => {
  // Track collapsed state for each rule
  const [collapsedRules, setCollapsedRules] = useState({});
  const { confirm, confirmDialog } = useConfirm();

  /**
   * Toggle rule collapsed state
   */
  const toggleCollapsed = (ruleId) => {
    setCollapsedRules((prev) => ({
      ...prev,
      [ruleId]: !prev[ruleId],
    }));
  };

  /**
   * Generate unique rule ID
   */
  const generateRuleId = () =>
    `rule_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

  /**
   * Add a new rule
   */
  const addRule = () => {
    const defaultRule = getDefaultRule
      ? getDefaultRule()
      : {
          id: generateRuleId(),
          enabled: true,
          name: `${__("New", "arraysubs")} ${ruleLabel}`,
          conditions: {
            logic: "and",
            rules: [],
          },
        };

    if (!defaultRule.id) {
      defaultRule.id = generateRuleId();
    }

    onChange([...rules, defaultRule]);
  };

  /**
   * Update a rule
   */
  const updateRule = (ruleId, updates) => {
    onChange(
      rules.map((rule) =>
        rule.id === ruleId ? { ...rule, ...updates } : rule,
      ),
    );
  };

  /**
   * Delete a rule
   */
  const deleteRule = async (ruleId) => {
    const ok = await confirm({
      title: __("Delete Rule", "arraysubs"),
      message: __("Are you sure you want to delete this rule?", "arraysubs"),
      confirmText: __("Delete", "arraysubs"),
      variant: "danger",
    });
    if (!ok) return;
    onChange(rules.filter((rule) => rule.id !== ruleId));
  };

  /**
   * Duplicate a rule
   */
  const duplicateRule = (rule) => {
    const newRule = {
      ...JSON.parse(JSON.stringify(rule)),
      id: generateRuleId(),
      name: `${rule.name} (${__("Copy", "arraysubs")})`,
    };

    const ruleIndex = rules.findIndex((r) => r.id === rule.id);
    const newRules = [...rules];
    newRules.splice(ruleIndex + 1, 0, newRule);
    onChange(newRules);
  };

  /**
   * Move rule up
   */
  const moveRuleUp = (index) => {
    if (index === 0) return;
    const newRules = [...rules];
    [newRules[index - 1], newRules[index]] = [
      newRules[index],
      newRules[index - 1],
    ];
    onChange(newRules);
  };

  /**
   * Move rule down
   */
  const moveRuleDown = (index) => {
    if (index === rules.length - 1) return;
    const newRules = [...rules];
    [newRules[index], newRules[index + 1]] = [
      newRules[index + 1],
      newRules[index],
    ];
    onChange(newRules);
  };

  /**
   * Toggle rule enabled status
   */
  const toggleRuleEnabled = (ruleId) => {
    updateRule(ruleId, {
      enabled: !rules.find((r) => r.id === ruleId)?.enabled,
    });
  };

  /**
   * Update conditions for a rule
   */
  const updateConditions = (ruleId, conditions) => {
    updateRule(ruleId, { conditions });
  };

  return (
    <div className="arraysubs-rule-builder">
      {/* Rules List */}
      {rules.length > 0 ? (
        <div className="arraysubs-rule-builder__rules">
          {rules.map((rule, index) => {
            const isCollapsed = collapsedRules[rule.id] ?? false;

            return (
              <div
                key={rule.id}
                className={`arraysubs-rule-builder__rule ${
                  !rule.enabled ? "arraysubs-rule-builder__rule--disabled" : ""
                } ${
                  isCollapsed ? "arraysubs-rule-builder__rule--collapsed" : ""
                }`}
              >
                {/* Rule Header */}
                <div className="arraysubs-rule-builder__rule-header">
                  <div
                    className="arraysubs-rule-builder__rule-icon"
                    title={__("Rule", "arraysubs")}
                  >
                    <List size={16} />
                  </div>

                  <label
                    className="arraysubs-rule-builder__rule-toggle"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <input
                      type="checkbox"
                      checked={rule.enabled !== false}
                      onChange={() => toggleRuleEnabled(rule.id)}
                    />
                    <span className="arraysubs-rule-builder__toggle-slider" />
                  </label>

                  <div
                    className="arraysubs-rule-builder__rule-info"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <input
                      type="text"
                      className="arraysubs-rule-builder__rule-name"
                      value={rule.name || ""}
                      onChange={(e) =>
                        updateRule(rule.id, { name: e.target.value })
                      }
                      placeholder={__("Rule name", "arraysubs")}
                    />
                    <span className="arraysubs-rule-builder__rule-number">
                      {ruleLabel} #{index + 1}
                    </span>
                  </div>

                  {/* Clickable area to collapse/expand */}
                  <div
                    className="arraysubs-rule-builder__rule-collapse-area"
                    onClick={() => toggleCollapsed(rule.id)}
                    title={
                      isCollapsed
                        ? __("Click to expand", "arraysubs")
                        : __("Click to collapse", "arraysubs")
                    }
                  />

                  <div
                    className="arraysubs-rule-builder__rule-actions"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <button
                      type="button"
                      className="arraysubs-rule-builder__action-btn"
                      onClick={() => moveRuleUp(index)}
                      disabled={index === 0}
                      title={__("Move up", "arraysubs")}
                    >
                      <ChevronUp size={16} />
                    </button>
                    <button
                      type="button"
                      className="arraysubs-rule-builder__action-btn"
                      onClick={() => moveRuleDown(index)}
                      disabled={index === rules.length - 1}
                      title={__("Move down", "arraysubs")}
                    >
                      <ChevronDown size={16} />
                    </button>
                    <button
                      type="button"
                      className="arraysubs-rule-builder__action-btn"
                      onClick={() => duplicateRule(rule)}
                      title={__("Duplicate", "arraysubs")}
                    >
                      <Copy size={16} />
                    </button>
                    <button
                      type="button"
                      className="arraysubs-rule-builder__action-btn arraysubs-rule-builder__action-btn--delete"
                      onClick={() => deleteRule(rule.id)}
                      title={__("Delete", "arraysubs")}
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>

                  {/* Collapse indicator */}
                  <button
                    type="button"
                    className="arraysubs-rule-builder__collapse-btn"
                    onClick={() => toggleCollapsed(rule.id)}
                    title={
                      isCollapsed
                        ? __("Expand", "arraysubs")
                        : __("Collapse", "arraysubs")
                    }
                  >
                    <ChevronRight
                      size={18}
                      className={`arraysubs-rule-builder__collapse-icon ${
                        !isCollapsed
                          ? "arraysubs-rule-builder__collapse-icon--expanded"
                          : ""
                      }`}
                    />
                  </button>
                </div>

                {/* Rule Body - collapsible */}
                {!isCollapsed && (
                  <div className="arraysubs-rule-builder__rule-body">
                    {/* Target Fields (optional - e.g., URL pattern, post type) */}
                    {renderTargetFields && (
                      <div className="arraysubs-rule-builder__section arraysubs-rule-builder__section--target">
                        <div className="arraysubs-rule-builder__section-header">
                          <span className="arraysubs-rule-builder__section-label">
                            {__("TARGET", "arraysubs")}
                          </span>
                        </div>
                        <div className="arraysubs-rule-builder__section-content">
                          {renderTargetFields(rule, (updates) =>
                            updateRule(rule.id, updates),
                          )}
                        </div>
                      </div>
                    )}

                    {/* Conditions (IF) */}
                    <div className="arraysubs-rule-builder__section arraysubs-rule-builder__section--conditions">
                      <div className="arraysubs-rule-builder__section-header">
                        <span className="arraysubs-rule-builder__section-label">
                          {__("IF", "arraysubs")}
                        </span>
                        <span className="arraysubs-rule-builder__section-hint">
                          {__("User meets these conditions", "arraysubs")}
                        </span>
                      </div>
                      <div className="arraysubs-rule-builder__section-content">
                        <ConditionBuilder
                          conditions={
                            rule.conditions || { logic: "and", rules: [] }
                          }
                          onChange={(conditions) =>
                            updateConditions(rule.id, conditions)
                          }
                          conditionTypes={conditionTypes}
                        />
                      </div>
                    </div>

                    {/* Actions (THEN) */}
                    {renderActionFields && (
                      <div className="arraysubs-rule-builder__section arraysubs-rule-builder__section--actions">
                        <div className="arraysubs-rule-builder__section-header">
                          <span className="arraysubs-rule-builder__section-label">
                            {__("THEN", "arraysubs")}
                          </span>
                          <span className="arraysubs-rule-builder__section-hint">
                            {__("Apply these actions", "arraysubs")}
                          </span>
                        </div>
                        <div className="arraysubs-rule-builder__section-content">
                          {renderActionFields(rule, (updates) =>
                            updateRule(rule.id, updates),
                          )}
                        </div>
                      </div>
                    )}

                    {/* Schedule (Content Dripping) */}
                    {showSchedule && (
                      <div className="arraysubs-rule-builder__section arraysubs-rule-builder__section--schedule">
                        <div className="arraysubs-rule-builder__section-header">
                          <span className="arraysubs-rule-builder__section-label">
                            {__("SCHEDULE", "arraysubs")}
                          </span>
                          <span className="arraysubs-rule-builder__section-hint">
                            {__(
                              "Delay access after subscription starts",
                              "arraysubs",
                            )}
                          </span>
                        </div>
                        <div className="arraysubs-rule-builder__section-content">
                          <ScheduleFields
                            rule={rule}
                            updateRule={(updates) =>
                              updateRule(rule.id, updates)
                            }
                          />
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        <div className="arraysubs-rule-builder__empty">
          <p>{__("No rules configured yet.", "arraysubs")}</p>
        </div>
      )}

      {/* Add Rule Button */}
      <div className="arraysubs-rule-builder__add">
        <button type="button" className="button" onClick={addRule}>
          <Plus size={16} />
          {__("Add New Rule", "arraysubs")}
        </button>
      </div>

      {confirmDialog}
    </div>
  );
};

export default RestrictionRuleBuilder;
