import React, { useState, useRef, useEffect } from "react";

interface RenameInputProps {
  value: string;
  onRename?: (newText: string) => void;
}

const RenameInput: React.FC<RenameInputProps> = ({ value, onRename }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [text, setText] = useState(value);
  const inputRef = useRef<HTMLInputElement | null>(null);
  useEffect(() => {
    setText(value); // Ensure state updates when parent value changes
  }, [value]);

  const handleDoubleClick = () => {
    setIsEditing(true);
    setTimeout(() => inputRef.current?.focus(), 0); // Focus the input after rendering
  };

  const handleBlur = () => {
    setIsEditing(false);
    if (onRename) {
      onRename(text);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      setIsEditing(false);
      if (onRename) {
        onRename(text);
      }
    }
  };

  return (
    <>
      {isEditing ? (
        <input
          ref={inputRef}
          type="text"
          value={text}
          onChange={handleChange}
          onBlur={handleBlur}
          onKeyDown={handleKeyDown}
          className="rename-input"
        />
      ) : (
        <span onDoubleClick={handleDoubleClick} className="input-value">
          {text}
        </span>
      )}
    </>
  );
};

export default RenameInput;
