import { FC, useCallback, useEffect, useState } from 'react';
import { Textarea } from '@/components/UI/Textarea';

interface TagsProps {
  tags: string[];
  onEnter: (tag: string) => void;
}

const Tags: FC<TagsProps> = ({ onEnter, tags }) => {
  const [value, setValue] = useState<string>('');

  const handleOnEnterKey = useCallback(
    (event: KeyboardEvent) => {
      if (event.code === 'Space' && value.trim()) {
        setValue('');
        onEnter(value.trim());
      }
    },
    [value, onEnter],
  );

  useEffect(() => {
    document.addEventListener('keydown', handleOnEnterKey);

    return () => {
      document.removeEventListener('keydown', handleOnEnterKey);
    };
  }, [handleOnEnterKey]);

  return (
    <div className='border-[1px] border-[#E6E9EE] rounded-lg flex gap-1 p-4'>
      {tags.map((tag, index) => (
        <span
          key={index}
          className='bg-[#E1EDF4] p-1 rounded-[4px] text-primary text-sm leading-[14px] h-[22px] w-max block'
        >
          {`#${tag}`}
        </span>
      ))}
      <Textarea
        onChange={(e) => setValue(e.target.value)}
        value={value}
        className='!border-0 w-full h-full !p-0'
      />
    </div>
  );
};

export default Tags;
