/**
 * ConditionRow Component
 *
 * A single condition row with type selector and dynamic fields (inline layout)
 *
 * @package ArraySubs
 */

import React, { useMemo } from "react";
import { __ } from "@wordpress/i18n";
import { Trash2 } from "lucide-react";
import AjaxSelect from "./AjaxSelect";

/**
 * ConditionRow Component
 *
 * @param {Object} props Component props
 * @param {Object} props.rule Current rule data
 * @param {Array} props.conditionTypes Available condition types
 * @param {Function} props.onChange Callback when rule changes
 * @param {Function} props.onDelete Callback when rule should be deleted
 */
const ConditionRow = ({ rule, conditionTypes, onChange, onDelete }) => {
  /**
   * Get the current condition type definition
   */
  const currentType = useMemo(() => {
    return (
      conditionTypes.find((t) => t.value === rule.type) || conditionTypes[0]
    );
  }, [rule.type, conditionTypes]);

  /**
   * Handle type change - reset fields to defaults
   */
  const handleTypeChange = (newType) => {
    const typeConfig = conditionTypes.find((t) => t.value === newType);
    const updates = { type: newType };

    // Set default values for the new type's fields
    if (typeConfig?.fields) {
      typeConfig.fields.forEach((field) => {
        if (field.defaultValue !== undefined) {
          updates[field.name] = field.defaultValue;
        } else if (field.multiple) {
          updates[field.name] = [];
        } else {
          updates[field.name] = "";
        }
      });
    }

    onChange(updates);
  };

  /**
   * Handle field value change
   */
  const handleFieldChange = (fieldName, value) => {
    onChange({ [fieldName]: value });
  };

  /**
   * Render a field based on its type - inline layout (no labels)
   */
  const renderField = (field) => {
    const value = rule[field.name];

    // Check if field should be shown based on dependency
    if (field.dependsOn && !rule[field.dependsOn]) {
      return null;
    }

    switch (field.type) {
      case "select":
        return (
          <select
            key={field.name}
            value={value || field.defaultValue || ""}
            onChange={(e) => handleFieldChange(field.name, e.target.value)}
            className="arraysubs-condition-row__select"
            title={field.label}
          >
            {field.options?.map((opt) => (
              <option key={opt.value || opt} value={opt.value || opt}>
                {opt.label || opt}
              </option>
            ))}
          </select>
        );

      case "number":
        return (
          <div
            key={field.name}
            className="arraysubs-condition-row__number-input"
          >
            {field.prefix && (
              <span className="arraysubs-condition-row__prefix">
                {field.prefix}
              </span>
            )}
            <input
              type="number"
              value={value ?? field.defaultValue ?? ""}
              onChange={(e) =>
                handleFieldChange(field.name, parseFloat(e.target.value) || 0)
              }
              min={field.min}
              max={field.max}
              step={field.step || 1}
              className="arraysubs-condition-row__input"
              title={field.label}
              placeholder={field.placeholder || field.label}
            />
            {field.suffix && (
              <span className="arraysubs-condition-row__suffix">
                {field.suffix}
              </span>
            )}
          </div>
        );

      case "text":
        return (
          <input
            key={field.name}
            type="text"
            value={value || ""}
            onChange={(e) => handleFieldChange(field.name, e.target.value)}
            placeholder={field.placeholder || field.label}
            className="arraysubs-condition-row__input arraysubs-condition-row__input--text"
            title={field.label}
          />
        );

      case "ajax_select":
        return (
          <div
            key={field.name}
            className="arraysubs-condition-row__ajax-select"
          >
            <AjaxSelect
              value={value}
              onChange={(newValue) => handleFieldChange(field.name, newValue)}
              endpoint={field.endpoint}
              multiple={field.multiple}
              placeholder={field.placeholder || field.label}
              dependsOnValue={field.dependsOn ? rule[field.dependsOn] : null}
            />
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="arraysubs-condition-row">
      {/* Type Selector */}
      <select
        value={rule.type || ""}
        onChange={(e) => handleTypeChange(e.target.value)}
        className="arraysubs-condition-row__type"
      >
        {conditionTypes.map((type) => (
          <option key={type.value} value={type.value}>
            {type.label}
          </option>
        ))}
      </select>

      {/* Dynamic Fields */}
      {currentType?.fields?.map((field) => renderField(field))}

      {/* Delete Button */}
      <button
        type="button"
        className="arraysubs-condition-row__delete"
        onClick={onDelete}
        title={__("Remove condition", "arraysubs")}
      >
        <Trash2 size={16} />
      </button>
    </div>
  );
};

export default ConditionRow;
