/**
 * FilterConditionRow Component
 *
 * Renders a single filter condition with field selector, operator selector, and value input.
 */

import { Minus } from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { FilterCondition, FilterOperator } from '../types/filter';
import { TriggerField } from '../types/trigger';
import {
  getOperatorsForType,
  getOperatorLabel,
  operatorRequiresValue,
} from '../constants/filter-operators';

interface FilterConditionRowProps {
  /** The condition to render */
  condition: FilterCondition;
  /** Available trigger fields */
  availableFields: TriggerField[];
  /** Callback when condition changes */
  onChange: (condition: FilterCondition) => void;
  /** Callback when condition should be removed */
  onRemove: () => void;
  /** Whether this is the only condition (disable remove if true) */
  isOnly: boolean;
}

export function FilterConditionRow({
  condition,
  availableFields,
  onChange,
  onRemove,
  isOnly,
}: FilterConditionRowProps) {
  // Get field type for the selected field
  const selectedField = availableFields.find((f) => f.name === condition.field);
  const fieldType = selectedField?.type || 'string';

  // Get operators for this field type
  const operators = getOperatorsForType(fieldType);

  // Check if value input should be shown
  const showValueInput = operatorRequiresValue(condition.operator);

  // Handle field change - reset operator if not valid for new field type
  const handleFieldChange = (fieldName: string) => {
    const newField = availableFields.find((f) => f.name === fieldName);
    const newFieldType = newField?.type || 'string';
    const newOperators = getOperatorsForType(newFieldType);

    // Keep operator if valid for new type, otherwise reset to first valid operator
    const newOperator = newOperators.includes(condition.operator)
      ? condition.operator
      : newOperators[0];

    onChange({
      ...condition,
      field: fieldName,
      operator: newOperator,
      // Clear value when changing field
      value: operatorRequiresValue(newOperator) ? '' : undefined,
    });
  };

  // Handle operator change
  const handleOperatorChange = (operator: FilterOperator) => {
    onChange({
      ...condition,
      operator,
      // Clear value if operator doesn't require it
      value: operatorRequiresValue(operator) ? (condition.value ?? '') : undefined,
    });
  };

  // Handle value change
  const handleValueChange = (value: string) => {
    // For boolean fields, convert string to boolean
    if (fieldType === 'boolean') {
      onChange({
        ...condition,
        value: value === 'true',
      });
      return;
    }

    // For integer fields, keep as string but validate as number
    onChange({
      ...condition,
      value,
    });
  };

  return (
    <div className="flex items-center gap-2 p-2 bg-slate-50 rounded">
      {/* Field Select */}
      <Select value={condition.field} onValueChange={handleFieldChange}>
        <SelectTrigger className="w-[180px] bg-white">
          <SelectValue placeholder="Select field" />
        </SelectTrigger>
        <SelectContent>
          {availableFields.map((field) => (
            <SelectItem key={field.name} value={field.name}>
              <span className="flex items-center gap-2">
                <span>{field.name}</span>
                <span className="text-xs text-slate-500">({field.type})</span>
              </span>
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* Operator Select */}
      <Select
        value={condition.operator}
        onValueChange={(v) => handleOperatorChange(v as FilterOperator)}
      >
        <SelectTrigger className="w-[160px] shrink-0 bg-white">
          <SelectValue placeholder="Operator" />
        </SelectTrigger>
        <SelectContent>
          {operators.map((op) => (
            <SelectItem key={op} value={op}>
              {getOperatorLabel(op)}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* Value Input */}
      {showValueInput && (
        <>
          {fieldType === 'boolean' ? (
            <Select value={condition.value?.toString() || ''} onValueChange={handleValueChange}>
              <SelectTrigger className="w-[100px] bg-white">
                <SelectValue placeholder="Value" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="true">True</SelectItem>
                <SelectItem value="false">False</SelectItem>
              </SelectContent>
            </Select>
          ) : fieldType === 'datetime' ? (
            <Input
              value={condition.value?.toString() || ''}
              onChange={(e) => handleValueChange(e.target.value)}
              placeholder="Select date/time"
              type="datetime-local"
              className="flex-1 min-w-[180px] bg-white"
            />
          ) : (
            <Input
              value={condition.value?.toString() || ''}
              onChange={(e) => handleValueChange(e.target.value)}
              placeholder={fieldType === 'integer' ? 'Number' : 'Value'}
              type={fieldType === 'integer' ? 'number' : 'text'}
              className="flex-1 min-w-[120px] bg-white"
            />
          )}
        </>
      )}

      {/* Spacer when no value input */}
      {!showValueInput && <div className="flex-1" />}

      {/* Remove Button */}
      <Button
        variant="ghost"
        size="sm"
        onClick={onRemove}
        disabled={isOnly}
        className="text-error hover:text-red-700 hover:bg-error-muted h-8 w-8 p-0"
        title={isOnly ? 'Cannot remove the only condition' : 'Remove condition'}
      >
        <Minus className="w-4 h-4" />
      </Button>
    </div>
  );
}
