import React, { useState, useEffect, useRef } from "react";
import { useUpdateNodeInternals } from "reactflow";
import { truncate } from "../../lib/utils";
import Item from "../../FlowManager/Item";
import "./Editable.css";

const Editable = ({
  setIsInEditMode,
  text,
  type,
  placeholder,
  callback,
  ...props
}: {
  setIsInEditMode: (value: boolean) => void;
  text: string;
  type: string;
  placeholder: string;
  callback: (value: string) => any;
  props: any;
}) => {
  const [isEditing, setEditing] = useState(false);
  const [value, setValue] = useState(text);

  const handleKeyDown = (event: any, type: any) => {
    const { key } = event;
    const keys = ["Escape", "Tab", "ArrowUp", "ArrowDown"];
    const enterKey = "Enter";
    const allKeys = [...keys, enterKey];
    if (
      (type === "textarea" && keys.indexOf(key) > -1) ||
      (type !== "textarea" && allKeys.indexOf(key) > -1)
    ) {
      setEditing(false);
      callback(value);
    }
  };

  return (
    <Item
      onSelect={() => {
        setIsInEditMode(true);
        setEditing(true);
      }}
    >
      <FolderIcon />
      {"Rename"}
      {isEditing ? (
        <div
          onBlur={() => {
            setEditing(false);
            callback(value);
          }}
          onKeyDown={(e) => {
            handleKeyDown(e, type);
          }}
        >
          <input
            onBlur={() => {
              setEditing(false);
              callback(value);
            }}
            autoFocus
            type="text"
            name={Math.random().toString(36).substring(7)}
            className="appearance-none border rounded w-full py-2 text-gray-700 leading-tight focus:outline-none focus:shadow-outline border-blue-300"
            style={{
              appearance: "none",
              paddingTop: "0.5rem",
              paddingBottom: "0.5rem",
              border: "1px solid #e2e8f0",
            }}
            placeholder={placeholder}
            value={value}
            onChange={(e) => setValue(e.target.value)}
          />
        </div>
      ) : (
        <p
          style={value ? { fontWeight: "bold" } : { fontWeight: "normal" }}
          className={`${value ? "text-black" : "text-gray-500"}`}
        >
          {truncate(value, 20) || placeholder || "Editable content"}
        </p>
      )}
    </Item>
  );
};

function FolderIcon() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
      className="w-6 h-6"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"
      />
    </svg>
  );
}

export default Editable;
