'use client';

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

import TextInput, { TextInputProps } from '@/components/input/TextInput';

interface DebouncedTextInputProps extends TextInputProps {
  delay?: number;
}

const DebouncedTextInput = (props: DebouncedTextInputProps) => {
  const { delay, onChange } = props;

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

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

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

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

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

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

export default DebouncedTextInput;
