/**
 * ConditionBuilder Component
 *
 * Builds condition list with AND/OR logic
 * Supports ONE level of grouping (flat > group, no nested groups)
 *
 * @package ArraySubs
 */

import React from "react";
import { __ } from "@wordpress/i18n";
import { Plus, FolderPlus, Trash2 } from "lucide-react";
import ConditionRow from "./ConditionRow";

/**
 * ConditionBuilder Component
 *
 * @param {Object} props Component props
 * @param {Object} props.conditions Current conditions object { logic: 'and'|'or', rules: [] }
 * @param {Function} props.onChange Callback when conditions change
 * @param {Array} props.conditionTypes Available condition types
 * @param {boolean} props.isNested Whether this is inside a group (prevents further nesting)
 */
const ConditionBuilder = ({
  conditions = { logic: "and", rules: [] },
  onChange,
  conditionTypes = [],
  isNested = false,
}) => {
  const { logic = "and", rules = [] } = conditions;

  /**
   * Update the logic operator (AND/OR)
   */
  const updateLogic = (newLogic) => {
    onChange({ ...conditions, logic: newLogic });
  };

  /**
   * Add a new condition rule
   */
  const addCondition = () => {
    const firstType = conditionTypes[0];
    const newRule = {
      id: `cond_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      type: firstType?.value || "lifetime_spent",
    };

    // Set default values from the field definitions
    if (firstType?.fields) {
      firstType.fields.forEach((field) => {
        if (field.defaultValue !== undefined) {
          newRule[field.name] = field.defaultValue;
        } else if (field.multiple) {
          newRule[field.name] = [];
        } else {
          newRule[field.name] = "";
        }
      });
    }

    onChange({
      ...conditions,
      rules: [...rules, newRule],
    });
  };

  /**
   * Add a new condition group (only at top level)
   */
  const addGroup = () => {
    if (isNested) return; // Prevent nested groups

    const newGroup = {
      id: `group_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      type: "group",
      logic: "or", // Default to OR for groups (common use case)
      rules: [],
    };

    onChange({
      ...conditions,
      rules: [...rules, newGroup],
    });
  };

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

  /**
   * Update a group's conditions
   */
  const updateGroupConditions = (groupId, newConditions) => {
    onChange({
      ...conditions,
      rules: rules.map((rule) =>
        rule.id === groupId ? { ...rule, ...newConditions } : rule,
      ),
    });
  };

  /**
   * Delete a rule
   */
  const deleteRule = (ruleId) => {
    onChange({
      ...conditions,
      rules: rules.filter((rule) => rule.id !== ruleId),
    });
  };

  return (
    <div className="arraysubs-condition-builder">
      {/* Empty state */}
      {rules.length === 0 ? (
        <div className="arraysubs-condition-builder__empty">
          <p>
            {__(
              "No conditions added. Click below to add conditions.",
              "arraysubs",
            )}
          </p>
        </div>
      ) : (
        <>
          {/* Logic Toggle - only show when multiple conditions */}
          {rules.length > 1 && (
            <div className="arraysubs-condition-builder__header">
              <span>{__("Match", "arraysubs")}</span>
              <div className="arraysubs-condition-builder__logic-toggle">
                <button
                  type="button"
                  className={logic === "and" ? "active" : ""}
                  onClick={() => updateLogic("and")}
                >
                  {__("ALL", "arraysubs")}
                </button>
                <button
                  type="button"
                  className={logic === "or" ? "active" : ""}
                  onClick={() => updateLogic("or")}
                >
                  {__("ANY", "arraysubs")}
                </button>
              </div>
              <span>{__("of these conditions", "arraysubs")}</span>
            </div>
          )}

          {/* Condition Rows */}
          <div className="arraysubs-condition-builder__list">
            {rules.map((rule, index) => (
              <div key={rule.id} className="arraysubs-condition-builder__item">
                {/* Logic separator between rules */}
                {index > 0 && (
                  <div className="arraysubs-condition-builder__separator">
                    <span>{logic === "and" ? "AND" : "OR"}</span>
                  </div>
                )}

                {/* Group or Condition */}
                {rule.type === "group" ? (
                  <div className="arraysubs-condition-builder__group">
                    <div className="arraysubs-condition-builder__group-header">
                      <span>{__("GROUP", "arraysubs")}</span>
                      <button
                        type="button"
                        onClick={() => deleteRule(rule.id)}
                        title={__("Delete Group", "arraysubs")}
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                    {/* Nested ConditionBuilder - no further nesting allowed */}
                    <ConditionBuilder
                      conditions={{ logic: rule.logic, rules: rule.rules }}
                      onChange={(newConditions) =>
                        updateGroupConditions(rule.id, newConditions)
                      }
                      conditionTypes={conditionTypes}
                      isNested={true}
                    />
                  </div>
                ) : (
                  <ConditionRow
                    rule={rule}
                    conditionTypes={conditionTypes}
                    onChange={(updates) => updateRule(rule.id, updates)}
                    onDelete={() => deleteRule(rule.id)}
                  />
                )}
              </div>
            ))}
          </div>
        </>
      )}

      {/* Add Buttons */}
      <div className="arraysubs-condition-builder__actions">
        <button type="button" onClick={addCondition}>
          <Plus size={14} />
          {__("Add Condition", "arraysubs")}
        </button>
        {/* Only show "Add Group" at top level (not nested) */}
        {!isNested && (
          <button type="button" onClick={addGroup}>
            <FolderPlus size={14} />
            {__("Add Group", "arraysubs")}
          </button>
        )}
      </div>
    </div>
  );
};

export default ConditionBuilder;
