import React, { useState, useEffect, useRef } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const EditableField = ({ value, onSave, onCancel }) => {
  const [editValue, setEditValue] = useState(value);
  const inputRef = useRef(null);

  useEffect(() => {
    // Focus input when component mounts
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      handleSave();
    } else if (e.key === "Escape") {
      handleCancel();
    }
  };

  const handleSave = () => {
    onSave(editValue);
  };

  const handleCancel = () => {
    onCancel();
  };

  return (
    <div className="flex items-center gap-2">
      <input
        ref={inputRef}
        type="text"
        value={editValue}
        onChange={(e) => setEditValue(e.target.value)}
        onKeyDown={handleKeyDown}
        className="w-full min-w-[100px] rounded border border-strokedark bg-transparent p-1 text-sm text-white outline-none focus:border-primary"
        placeholder="Enter value"
      />
      <div className="flex gap-1">
        <button
          onClick={handleSave}
          className="rounded p-1 hover:bg-primary/20"
          title="Save"
        >
          <FontAwesomeIcon
            icon="fa-solid fa-check"
            className="h-3 w-3 text-green-500"
          />
        </button>
        <button
          onClick={handleCancel}
          className="rounded p-1 hover:bg-primary/20"
          title="Cancel"
        >
          <FontAwesomeIcon
            icon="fa-solid fa-xmark"
            className="h-3 w-3 text-red-500"
          />
        </button>
      </div>
    </div>
  );
};

export default EditableField;
