import React, { useState } from 'react';
import Tag from './Tag.js';
import './TagInput.css';

function TagInput({
  maxKeywords = 0,
  placeholder = '',
  tags = [],
  setTags = (_) => {},
  ...props
}: {
  maxKeywords?: number;
  placeholder?: string;
  tags: string[];
  setTags: (_: string[]) => void;
}) {
  const [currentInput, setCurrentInput] = useState<string>('');
  const [duplicateError, setDuplicateError] = useState<boolean>(false);

  const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      addTag();
    } else if (e.key === 'Backspace' && currentInput === '' && tags.length > 0) {
      removeTag(tags.length - 1);
    }
  };

  const handleTagRemoveClick = (e: React.MouseEvent<HTMLButtonElement>, index: number): void => {
    e.stopPropagation();
    removeTag(index);
  };

  const addTag = (): void => {
    setDuplicateError(false);
    const trimmed = currentInput.trim();
    if (trimmed && (maxKeywords === 0 || tags.length < maxKeywords) && !tags.includes(trimmed)) {
      setTags([...tags, trimmed]);
      setCurrentInput('');
    }

    if (tags.includes(trimmed)) {
      setDuplicateError(true);
    }
  };

  const removeTag = (index: number): void => {
    setTags(tags.filter((_, i) => i !== index));
  };

  return (
    <>
      <label className="tag-input" htmlFor="tag-input">
        <div className="tag-input__tags">
          {tags.map((tag, index) => (
            <Tag key={tag} remove={(e) => handleTagRemoveClick(e, index)}>
              {tag}
            </Tag>
          ))}
          {(maxKeywords === 0 || tags.length < maxKeywords) && (
            <input
              id="tag-input"
              type="text"
              value={currentInput}
              onChange={(e: React.ChangeEvent<HTMLInputElement>): void => {
                setDuplicateError(false);
                setCurrentInput(e.target.value);
              }}
              onKeyDown={handleInputKeyDown}
              onBlur={addTag}
              placeholder={tags.length === 0 ? placeholder : ''}
              className="tag-input__input"
              {...props}
            />
          )}
        </div>
      </label>
      {duplicateError && (
        <div role="alert" className="tag-input__duplicate-error">
          Duplicate tags are not allowed
        </div>
      )}
    </>
  );
}

export default TagInput;
