/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React, {useState, useEffect, KeyboardEvent} from 'react';
import {v4 as uuid} from 'uuid';

import {Tag} from 'components/tags';
import {Label} from 'components/forms/label';
import Input from 'components/forms/Input';
import {InputWithTagsWrapper, TagContainer, TagWrapper, TagButton} from './style';

interface IInputWithTags {
  label?: string;
  labelColor?: string;
  labelIcon?: React.JSX.Element;
  labelClassName?: string;
  error?: boolean;
  helperText?: string;
  helperTextClassName?: string;
  onTagListChange: (tags: string[]) => void;
  defaultValue?: string[];
  id?: string;
  width?: number | string;
}

const InputWithTags = ({
  label,
  labelColor,
  labelIcon,
  labelClassName,
  onTagListChange,
  defaultValue,
  id: propsId,
  helperText,
  helperTextClassName,
  error,
  width
}: IInputWithTags): React.JSX.Element => {
  const [tagInput, setTagInput] = useState('');
  const [tags, setTags] = useState(defaultValue || []);
  const id = propsId || uuid();

  useEffect(() => {
    onTagListChange(tags);
  }, [tags, onTagListChange]);

  const addTag = () => {
    if (!tagInput.length) {
      return;
    }

    const exists = tags.filter(tag => tag.toLowerCase() === tagInput.toLowerCase()).length > 0;

    if (!exists) {
      setTags([...tags, tagInput]);
      setTagInput('');
    }
  };

  const handleOnKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      addTag();
    }
  };

  const onClose = (tag: string) => {
    const newSetOfTags = tags.filter(currentTag => currentTag !== tag);

    setTags(newSetOfTags);
  };

  return (
    <InputWithTagsWrapper width={width}>
      {label && <Label htmlFor={id} text={label} color={labelColor} icon={labelIcon} className={labelClassName} />}
      <TagWrapper>
        <Input
          id={id}
          onChange={({target}) => setTagInput(target.value)}
          value={tagInput}
          onKeyDown={handleOnKeyDown}
          name="testId-downloadInputField"
          className="testId-streamTags"
          helperText={helperText}
          helperTextClassName={helperTextClassName}
          error={error}
        />
        <TagButton disabled={!tagInput.length} onClick={addTag}>
          Add
        </TagButton>
      </TagWrapper>
      {tags.length > 0 && (
        <TagContainer>
          {tags.map(tag => (
            <Tag key={tag} label={tag} onClose={() => onClose(tag)} />
          ))}
        </TagContainer>
      )}
    </InputWithTagsWrapper>
  );
};

export default InputWithTags;
