/**
 * FilterGroupBuilder Component
 *
 * Recursive component for building nested AND/OR filter groups.
 */

import { Plus, Trash2 } from 'lucide-react';
import { Button } from './ui/button';
import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group';
import { FilterConditionRow } from './FilterConditionRow';
import { FilterCondition, FilterGroup, isFilterGroup, FilterLogic } from '../types/filter';
import { TriggerField } from '../types/trigger';
import { __ } from '@/lib/i18n';
import { useCapabilities } from '@/hooks/useCapabilities';

interface FilterGroupBuilderProps {
  /** The filter group to render */
  group: FilterGroup;
  /** Available trigger fields */
  availableFields: TriggerField[];
  /** Callback when group changes */
  onChange: (group: FilterGroup) => void;
  /** Callback when group should be removed (only for nested groups) */
  onRemove?: () => void;
  /** Current nesting depth */
  depth?: number;
}

export function FilterGroupBuilder({
  group,
  availableFields,
  onChange,
  onRemove,
  depth = 0,
}: FilterGroupBuilderProps) {
  // Add a new condition to the group
  const handleAddCondition = () => {
    const defaultField = availableFields[0]?.name || '';
    const newCondition: FilterCondition = {
      field: defaultField,
      operator: 'equals',
      value: '',
    };
    onChange({
      ...group,
      conditions: [...group.conditions, newCondition],
    });
  };

  // Add a new nested group
  const handleAddGroup = () => {
    const defaultField = availableFields[0]?.name || '';
    // Alternate logic: if parent is AND, child is OR and vice versa
    const childLogic: FilterLogic = group.logic === 'and' ? 'or' : 'and';
    const newGroup: FilterGroup = {
      logic: childLogic,
      conditions: [
        {
          field: defaultField,
          operator: 'equals',
          value: '',
        },
      ],
    };
    onChange({
      ...group,
      conditions: [...group.conditions, newGroup],
    });
  };

  // Toggle between AND/OR logic
  const handleToggleLogic = (newLogic: string) => {
    if (newLogic && (newLogic === 'and' || newLogic === 'or')) {
      onChange({
        ...group,
        logic: newLogic as FilterLogic,
      });
    }
  };

  // Update a condition or nested group at index
  const handleConditionChange = (index: number, newCondition: FilterCondition | FilterGroup) => {
    const newConditions = [...group.conditions];
    newConditions[index] = newCondition;
    onChange({ ...group, conditions: newConditions });
  };

  // Remove a condition or nested group at index
  const handleRemoveCondition = (index: number) => {
    onChange({
      ...group,
      conditions: group.conditions.filter((_, i) => i !== index),
    });
  };

  const isNested = depth > 0;
  // Only allow adding nested groups at the root level (first layer)
  const { nestedFilters } = useCapabilities();
  const canAddNestedGroup = nestedFilters && depth === 0;

  return (
    <div
      className={`border rounded p-3 ${
        isNested ? 'ml-4 border-dashed border-slate-300 bg-white' : 'border-slate-200'
      }`}
    >
      {/* Group Header */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-3">
          <ToggleGroup
            type="single"
            value={group.logic}
            onValueChange={handleToggleLogic}
            className="bg-slate-100 rounded p-0.5"
          >
            <ToggleGroupItem
              value="and"
              className="text-xs px-3 py-1 h-7 data-[state=on]:bg-white data-[state=on]:shadow-sm"
            >
              {__('AND')}
            </ToggleGroupItem>
            <ToggleGroupItem
              value="or"
              className="text-xs px-3 py-1 h-7 data-[state=on]:bg-white data-[state=on]:shadow-sm"
            >
              {__('OR')}
            </ToggleGroupItem>
          </ToggleGroup>
          <span className="text-xs text-slate-500">
            {group.logic === 'and'
              ? __('All conditions must match')
              : __('Any condition can match')}
          </span>
        </div>

        {onRemove && (
          <Button
            variant="ghost"
            size="sm"
            onClick={onRemove}
            className="text-error hover:text-red-700 hover:bg-error-muted h-8 w-8 p-0"
            title={__('Remove group')}
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        )}
      </div>

      {/* Conditions */}
      <div className="space-y-2">
        {group.conditions.map((condition, index) => (
          <div key={index}>
            {isFilterGroup(condition) ? (
              // Nested group
              <FilterGroupBuilder
                group={condition}
                availableFields={availableFields}
                onChange={(newGroup) => handleConditionChange(index, newGroup)}
                onRemove={() => handleRemoveCondition(index)}
                depth={depth + 1}
              />
            ) : (
              // Single condition
              <FilterConditionRow
                condition={condition}
                availableFields={availableFields}
                onChange={(newCond) => handleConditionChange(index, newCond)}
                onRemove={() => handleRemoveCondition(index)}
                isOnly={group.conditions.length === 1}
              />
            )}
          </div>
        ))}
      </div>

      {/* Add Buttons */}
      <div className="flex gap-2 mt-3">
        <Button variant="outline" size="sm" onClick={handleAddCondition} className="text-xs">
          <Plus className="w-3.5 h-3.5 mr-1" />
          {__('Add Condition')}
        </Button>
        {canAddNestedGroup && (
          <Button variant="outline" size="sm" onClick={handleAddGroup} className="text-xs">
            <Plus className="w-3.5 h-3.5 mr-1" />
            {__('Add Group')}
          </Button>
        )}
      </div>
    </div>
  );
}
