import { useCallback } from 'react';

import TextareaV2 from '../textarea/TextareaV2';

export type CaptionInputProps = {
  parentClip?: boolean;
  showDisplayTags?: boolean;
  showContestToggle?: boolean;
  currentCaption: string;
  setCurrentCaption: (caption: string) => void;
  onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  ref: React.RefObject<HTMLTextAreaElement | null>;
};

const CaptionInput = ({
  parentClip,
  showDisplayTags,
  showContestToggle,
  currentCaption,
  setCurrentCaption,
  onKeyDown,
  ref,
}: CaptionInputProps) => {
  const handleTextareaKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
      // allow passed-in onKeyDown handling which can call e.preventDefault() to kill the rest of this logic
      onKeyDown?.(e);
      if (!e.isDefaultPrevented()) {
        if (e.key === 'Tab') {
          e.preventDefault();
        }
      }
    },
    [onKeyDown]
  );

  return (
    <TextareaV2
      minRows={parentClip ? 2 : showDisplayTags ? 4 : 6}
      maxRows={parentClip ? (showContestToggle ? 2 : 4) : 6}
      maxLength={500}
      value={currentCaption || ''}
      resize={true}
      onChange={(e) => {
        const filteredValue = e.target.value.replace(/\n/g, '');
        setCurrentCaption(filteredValue);
      }}
      onKeyDown={handleTextareaKeyDown}
      placeholder={'Add a caption...'}
      ref={ref}
    />
  );
};

export default CaptionInput;
