import { useState } from '@wordpress/element';

const TokenField = ({ value = [], suggestions = [], onChange, placeholder = '' }) => {
  const [inputValue, setInputValue] = useState('');

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      const newToken = inputValue.trim();
      if (newToken && !value.includes(newToken)) {
        onChange([...value, newToken]);
        setInputValue('');
      }
    } else if (e.key === 'Backspace' && inputValue === '' && value.length > 0) {
      onChange(value.slice(0, -1));
    }
  };

  const removeToken = (tokenToRemove) => {
    onChange(value.filter(token => token !== tokenToRemove));
  };

  return (
    <div className="pr:token-field pr:border pr:border-gray-300 pr:rounded-md pr:p-2 pr:flex pr:flex-wrap pr:gap-2 pr:transition-all pr:duration-300">
      {value.map((token) => (
        <span
          key={token}
          className="pr:inline-flex pr:items-center pr:bg-primary-100 pr:text-primary-800 pr:px-3 pr:py-1 pr:rounded-full pr:text-sm pr:transition-all pr:duration-300"
        >
          {token}
          <button
            type="button"
            onClick={() => removeToken(token)}
            className="pr:ml-2 pr:text-primary-600 pr:hover:text-primary-800 pr:transition-all pr:duration-300"
          >
            ×
          </button>
        </span>
      ))}
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder={value.length === 0 ? placeholder : ''}
        className="pr:flex-1 pr:min-w-[120px] pr:outline-hidden pr:border-none pr:bg-transparent pr:transition-all pr:duration-300"
      />
    </div>
  );
};

export default TokenField;
