/**
 * Key-Value Field Component
 *
 * Renders a dynamic key-value pair editor for custom fields mapping.
 * Supports both manual key entry and select-from-list for keys.
 */

import { memo } from 'react';
import { Plus, Minus, Loader2 } from 'lucide-react';
import { Label } from '../ui/label';
import { Input } from '../ui/input';
import { Button } from '../ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { VariableInput } from '../VariableInput';
import { ActionField } from '../../types/action';
import { AvailableContext } from '../../hooks/useAvailableContext';

interface KeyValueFieldProps {
  fieldName: string;
  field: ActionField;
  value: Record<string, string>;
  availableKeys: Array<Record<string, string>>;
  isLoading: boolean;
  onChange: (value: Record<string, string>) => void;
  availableContext: AvailableContext;
  error?: string;
  fieldError?: string;
  dependencyMet: boolean;
  dependencyLabel?: string;
}

export const KeyValueField = memo(function KeyValueField({
  fieldName: _fieldName,
  field,
  value,
  availableKeys,
  isLoading,
  onChange,
  availableContext,
  error,
  fieldError,
  dependencyMet,
  dependencyLabel,
}: KeyValueFieldProps) {
  const keyValuePairs = value || {};

  const handleAddPair = () => {
    onChange({ ...keyValuePairs, '': '' });
  };

  const handleRemovePair = (keyToRemove: string) => {
    const newPairs = { ...keyValuePairs };
    delete newPairs[keyToRemove];
    onChange(newPairs);
  };

  const handleKeyChange = (oldKey: string, newKey: string) => {
    const newPairs: Record<string, string> = {};
    Object.entries(keyValuePairs).forEach(([k, v]) => {
      if (k === oldKey) {
        newPairs[newKey] = v;
      } else {
        newPairs[k] = v;
      }
    });
    onChange(newPairs);
  };

  const handleValueChange = (key: string, newValue: string) => {
    onChange({ ...keyValuePairs, [key]: newValue });
  };

  return (
    <div className="space-y-2">
      <Label className="text-slate-900">
        {field.label}
        {field.required && <span className="text-red-600 ml-1">*</span>}
      </Label>

      {!dependencyMet && field.depends_on && (
        <p className="text-xs text-slate-500">
          Select {dependencyLabel || field.depends_on.replace('_', ' ')} first to configure custom fields.
        </p>
      )}

      {dependencyMet && isLoading && (
        <div className="flex items-center gap-2 py-2">
          <Loader2 className="w-4 h-4 animate-spin text-cyan-600" />
          <span className="text-sm text-slate-500">Loading custom fields...</span>
        </div>
      )}

      {dependencyMet && !isLoading && (
        <div className="space-y-2">
          {Object.entries(keyValuePairs).map(([key, val], index) => (
            <div key={index} className="flex gap-2 items-start">
              {availableKeys.length > 0 ? (
                <Select value={key} onValueChange={(newKey) => handleKeyChange(key, newKey)}>
                  <SelectTrigger className="w-1/3 border-slate-400">
                    <SelectValue placeholder="Field" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableKeys.map((keyOption) => {
                      const keyValue = field.key_field ? keyOption[field.key_field] : keyOption.Key;
                      const keyLabel = field.label_field
                        ? keyOption[field.label_field]
                        : keyOption.FieldName;
                      return (
                        <SelectItem key={keyValue} value={keyValue}>
                          {keyLabel}
                        </SelectItem>
                      );
                    })}
                  </SelectContent>
                </Select>
              ) : (
                <Input
                  value={key}
                  onChange={(e) => handleKeyChange(key, e.target.value)}
                  placeholder="Field key"
                  className="w-1/3 border-slate-400"
                />
              )}
              <div className="flex-1">
                <VariableInput
                  value={val}
                  onChange={(newValue) => handleValueChange(key, newValue)}
                  availableContext={availableContext}
                  placeholder="Value"
                />
              </div>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => handleRemovePair(key)}
                className="text-error hover:text-red-700 p-1 h-auto"
              >
                <Minus className="w-4 h-4" />
              </Button>
            </div>
          ))}
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleAddPair}
            className="w-full border-dashed"
          >
            <Plus className="w-4 h-4 mr-2" />
            Add Custom Field
          </Button>
        </div>
      )}

      <p className="text-xs text-slate-500">{field.description}</p>
      {error && <p className="text-xs text-red-600">{error}</p>}
      {fieldError && <p className="text-xs text-red-600">{fieldError}</p>}
    </div>
  );
});
