'use client';

import { ChangeEvent, ChangeEventHandler, useEffect, useState } from 'react';
import { useDebounce } from 'use-debounce';

import TextArea, { TextAreaProps } from '@/components/input/TextArea';

interface DebouncedTextAreaProps extends TextAreaProps {
  delay?: number;
}

const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
  const { delay, onChange } = props;

  const [internalChangeEvent, setInternalChangeEvent] =
    useState<ChangeEvent<HTMLTextAreaElement>>();
  const [internalValue, setInternalValue] = useState(props.value);

  const [debouncedChangeEvent] = useDebounce(internalChangeEvent, delay ?? 300);
  const [debouncedValue] = useDebounce(internalValue, delay ?? 300);

  const internalChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (
    e
  ) => {
    setInternalValue(e.target.value);
    setInternalChangeEvent(e);
  };

  useEffect(() => {
    if (debouncedChangeEvent) {
      onChange?.(debouncedChangeEvent);
    }
  }, [debouncedValue]);

  return (
    <TextArea
      {...props}
      value={internalValue}
      onChange={internalChangeHandler}
    />
  );
};

export default DebouncedTextArea;
