'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;
  ref?: React.RefObject<HTMLTextAreaElement | null>;
}

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);

  // Sync internal value with external props.value when it changes (e.g., form reset)
  useEffect(() => {
    setInternalValue(props.value);
  }, [props.value]);

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

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

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

export default DebouncedTextArea;
