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

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

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

const RenameInput: React.FC<RenameInputProps> = ({ value, onRename, checkDuplicate, canEdit = true }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [text, setText] = useState(value);
  const [isDuplicate, setIsDuplicate] = useState(false);
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    setText(value);
  }, [value]);

  useEffect(() => {
    if (checkDuplicate) {
      setIsDuplicate(checkDuplicate(text));
    }
  }, [text, checkDuplicate]);

  const handleDoubleClick = () => {
    if (canEdit) {
      setIsEditing(true);
      setTimeout(() => inputRef.current?.focus(), 0);
    }
  };

  const handleBlur = () => {

    if (isDuplicate) return
    setIsEditing(false);
    if (onRename && !isDuplicate) {
      onRename(text);
    }
  };

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

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

  return (
    <>
      {isEditing ? (
        <>
          <input
            ref={inputRef}
            type="text"
            value={text}
            onChange={handleChange}
            onBlur={handleBlur}
            onKeyDown={handleKeyDown}
            className={`rename-input ${isDuplicate ? "input-error" : ""}`}
          />
          {/* {isDuplicate && <div className="error-msg">Name already exists!</div>} */}
        </>
      ) : (
        <span onDoubleClick={handleDoubleClick} className="input-value">
          {text}
        </span>
      )}
    </>
  );
};
export default RenameInput
