import { useState } from 'react';
import { useTranslation } from 'react-i18next';

interface StringArrayEditorProps {
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
}

export function StringArrayEditor({ value, onChange, placeholder }: StringArrayEditorProps) {
  const { t } = useTranslation('settings');
  const [input, setInput] = useState('');

  const handleAdd = () => {
    const trimmed = input.trim();
    if (!trimmed) return;
    onChange([...value, trimmed]);
    setInput('');
  };

  const handleRemove = (index: number) => {
    onChange(value.filter((_, i) => i !== index));
  };

  return (
    <div>
      <div className="flex gap-1 mb-1">
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); handleAdd(); } }}
          placeholder={placeholder}
          className="flex-1 px-3 py-1.5 text-sm border border-slate-300 rounded-lg focus:ring-2 focus:ring-accent-ring focus:border-accent outline-none"
        />
        <button
          onClick={handleAdd}
          className="px-3 py-1.5 text-sm bg-accent text-accent-fg rounded-lg hover:bg-accent-deep"
        >
          {t('stringArray.add')}
        </button>
      </div>
      {value.length > 0 && (
        <div className="flex flex-wrap gap-1 mt-1">
          {value.map((item, i) => (
            <span key={i} className="inline-flex items-center gap-1 px-2 py-0.5 text-xs bg-slate-100 text-slate-700 rounded">
              {item}
              <button onClick={() => handleRemove(i)} className="text-slate-400 hover:text-red-500">&times;</button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
